Implementation for a relatively basic programming challenge:
Find the first unique character in a string
So evaluating the string ABCA
would return B
.
My implementation does the following:
- Initialize a
boolean
array that is the size of the input string - note that the default initialization value isfalse
- The
boolean
array's values correspond to whether or not the input string character that shares the same index value is unique or not. - Compare each character in the input string against all the characters to the right of it
- If there is a match, set the values in the boolean array to true for each character index value.
- Iterate through the boolean array and return the first value that is false.
- If iteration completes, throw a
NoUniqueCharacters
Exception
Is there a better approach?
- I briefly considered using some sort of
Ordered Map
(if such a thing exists) that maps characters to their counts where the characterkey
values are ordered by their index in the string
public Character identifyFirstUniqueCharacterInString(final String string) throws NoUniqueCharactersException {
final char[] chars = string.toCharArray();
final boolean[] repeatedCharacterIndices = new boolean[chars.length];
for (int candidateCharacterIndex = 0; candidateCharacterIndex < chars.length; candidateCharacterIndex++) {
for (int comparisonCharacterIndex = candidateCharacterIndex + 1; comparisonCharacterIndex < chars.length; comparisonCharacterIndex++) {
if (chars[candidateCharacterIndex] == chars[comparisonCharacterIndex]) {
repeatedCharacterIndices[candidateCharacterIndex] = true;
repeatedCharacterIndices[comparisonCharacterIndex] = true;
}
}
}
for (int repeatedCharacterIndex = 0; repeatedCharacterIndex < repeatedCharacterIndices.length; repeatedCharacterIndex++) {
if (!repeatedCharacterIndices[repeatedCharacterIndex]) {
return chars[repeatedCharacterIndex];
}
}
throw new NoUniqueCharactersException();
}