Skip to content

Instantly share code, notes, and snippets.

@rayjcwu
Last active August 29, 2015 13:56
Show Gist options
  • Select an option

  • Save rayjcwu/8967422 to your computer and use it in GitHub Desktop.

Select an option

Save rayjcwu/8967422 to your computer and use it in GitHub Desktop.
char unique (String str) {
HashMap<Character, Integer> map = new HashMap<Character, Integer>();
Set<Character> set = new SortedHashSet<Character>();
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
if (map.containsKey(c)) {
map.put(c, map.get(c) + 1);
set.remove(c);
} else {
map.put(c, 1);
set.add(c);
}
}
if (set.size() == 0) {
throw new NoUniqueCharException();
} else {
for (Character c: set) {
return c;
}
}
}
char unique2 (String str) {
LinkedHashMap<Character, Integer> map = new LinkedHashMap<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 (Map.Entry<Character, Integer> e: map.entrySet()) {
if (e.getValue() == 1) {
return e.getKey();
}
}
throw new NoUniqueCharException();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment