How about this one? It's a regex solution rather than a loop:
public static int countUniqueCharacters(String input)
{
String unique = input.replaceAll("(.)(?=.*?\\1)", "");
return unique.length();
}
If the program needs to be case-insensitive, you can use this instead:
public static int countUniqueCharacters(String input)
{
String unique = input.replaceAll("(?i)(.)(?=.*?\\1)", "");
return unique.length();
}
You could make this a single-line method with return input.replaceAll(...).length();
Regex Explained:
.
matches any character
(...)
creates a capturing group, to be referenced later
(?=...)
creates a lookahead, to look forwards in the input
.*?
matches anything between the character and its match (non-greedy matching)
\\1
matches the first capturing group
(?i)
sets the case-insensitive flag
So, the regex will look for any character which has a duplicate later in the string, and then replaceAll
will replace it with the empty string. So, an input like "cabbacbdbadbcabdaadcb"
becomes "adcb"
(keeping the last of each unique character). Then, with a string containing unique characters, that string's length is the answer.
If, for some reason, you needed the unique-character string and you needed it in the original order, you would have to reverse the original string before stripping away duplicate characters (and then reverse it again when you're done). This would require either a third-party library, StringBuffer
, or a loop.