Created
April 13, 2015 15:34
-
-
Save genman/898334599ef210607ea6 to your computer and use it in GitHub Desktop.
getFirstNonRepeatedLetter
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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