Skip to content

Instantly share code, notes, and snippets.

@genman
Created April 13, 2015 15:34
Show Gist options
  • Save genman/898334599ef210607ea6 to your computer and use it in GitHub Desktop.
Save genman/898334599ef210607ea6 to your computer and use it in GitHub Desktop.
getFirstNonRepeatedLetter
class GetFirstNonRepeatedLetter
static final int REPEAT = -1;
public static Character getFirstNonRepeatedLetter(String word) {
// check if the word is null
if (word == null) throw new NullPointerException()
// store a count of character occurrences
Map<Character, Integer> map = new HashMap<Character, Integer>();
for (int i = 0; i < word.length(); i++) {
char c = word.charAt(i)
// if character exists, mark as REPEAT
if (map.containsKey(c)) {
map.put(c, REPEAT);
} else {
// put the char and the index of the char
map.put(c, i);
}
}
int min = Integer.MAX_VALUE;
Character nonRepeatLetter = null;
for (Map.Entry<Character, Integer> entry : map.entrySet()) {
int i = entry.getValue()
if (i == REPEAT)
continue;
// initialize the count
if (i < min) {
min = i;
nonRepeatLetter = entry.getKey();
}
}
return nonRepeatLetter;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment