Counting unique characters in a String given by the user
java
Solution
It is extremely easy :)
public static int countUniqueCharacters(String input) {
boolean[] isItThere = new boolean[Character.MAX_VALUE];
for (int i = 0; i < input.length(); i++) {
isItThere[input.charAt(i)] = true;
}
int count = 0;
for (int i = 0; i < isItThere.length; i++) {
if (isItThere[i] == true){
count++;
}
}
return count;
}
Example for input "aab"
First for-cycle goes 3 times, each time for one char.
Value of "a" is 97, so it turns isItThere[97] to true, then second "a" is involved, which is doing the same, isItThere[97] is set to true again (hence changing nothing).
After that "b" is involved, value of char "b" is 98, therefore isItThere[98] is set to true.
And then you have second for-cycle, where you cycle through the all isItThere array. If you find any true statement, you increment count. In our case, you find isItThere[97] and isItThere[98] as true statement, it means you increment twice and returning 2.
Problem
I have to write a program that counts the uniques characters in a String given by the user. For example "abc" returns 3 and "aabbccd" returns 4. I am not allow to use advanced Java classes like Map, Set, etc. I can only use arrays, Strings, for loops, while loops, if statements. I am trying to use a nested loop but am getting confused about how to write the algorithm for the second for loop. ``` public static int countUniqueCharacters(String input){ String orgInput = input.toLowerCase(); int count = 0; int stringLength = input.length(); for( int i = 0; i<stringLength; i++){ for(int j = 2; j > j-i-1; j--){ char temp = orgInput.charAt(i); if (temp == orgInput.charAt(j)){ count++; ```