Comment on: We need more programming challenges. We should start off small: First non-repeating character of a string. Any language you like.
2 16 Apr 2016 13:21 u/Owoc in v/programmingComment on: We need more programming challenges. We should start off small: First non-repeating character of a string. Any language you like.
Java:
public static char findFirstNonRepeatingCharacter(String s) {
if (s.isEmpty()) {
throw new IllegalArgumentException();
}
LinkedHashMap<Character, Integer> occurrences = new LinkedHashMap<>();
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (occurrences.containsKey(c)) {
occurrences.put(c, occurrences.get(c) + 1);
} else {
occurrences.put(c, 1);
}
}
for (Character c : occurrences.keySet()) {
if (occurrences.get(c) == 1) {
return c.charValue();
}
}
throw new RuntimeException();
}
It could alternatively be written like MrKequc's snippet to be much more concise, but slower: