I was doing this problem on Firecode.io where:
firstNonRepeatedCharacter( "abcdcd" ) --> 'a'
firstNonRepeatedCharacter( "cbcd" ) --> 'b'
firstNonRepeatedCharacter( "cdcd" ) --> null
The solution I came up with was:
public static Character firstNonRepeatedCharacter(String str) {
if (str == null) return null;
Hashtable<Character, Integer> map = new Hashtable<Character, Integer>();
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
if (map.containsKey(c)) {
map.put(c, map.get(c) + 1);
} else {
map.put(c, 1);
}
}
for (Character key : map.keySet()) {
if (map.get(key) == 1) return key;
}
return null;
}
This failed for the first test case and got:
firstNonRepeatedCharacter( "abcdcd" ) --> 'b' // 'a' is correct
I realized I was assuming insert order, so I gave HashMap
a try:
Map<Character, Integer> map = new HashMap<Character, Integer>();
which ended up passing all the cases.
Based on what I read however, HashMap
should often be used over Hashtable
, but HashMap
doesn't even guarantee support order, and LinkedHashMap
does. Is this correct? I just got lucky with the test cases and should be using LinkedHashMap
?