First Unique Character in a String
Given a string, find the first non-repeating character in it and return its index. If it doesn’t exist, return -1.
unique->hashset.
but hashset can only do binary things, like if I find again, the only way to show I found again is remove this key, but what if they appear third time? do I have to re-add that?
so instead, I use hashmap.
class Solution {
public int firstUniqChar(String s) {
if (s == null || s.length() == 0) return -1;
HashMap<Character, Boolean> map = new HashMap();
for (int i = 0; i < s.length(); i++) {
if (map.containsKey(s.charAt(i))) {
map.put(s.charAt(i), false);
} else {
map.put(s.charAt(i), true);
}
}
for (int i = 0; i < s.length(); i++) {
if (map.get(s.charAt(i))) { //if it is true, means this is the only one in whole string
return i;
}
}
return -1;
}
}

浙公网安备 33010602011771号