public int firstUniqChar(String s) {
if (s == null || s.isEmpty()) {
return -1;
}
int n = s.length();
// <char, loc>
HashMap<Character, Integer> exist = new HashMap<>();
boolean[] record = new boolean[n];
// process dup from back
for (int i = n - 1; i >= 0; i--) {
char c = s.charAt(i);
if (!exist.containsKey(c)) {
record[i] = true;
exist.put(c, i);
} else {
record[exist.get(c)] = false;
}
}
// find first from front
for (int i = 0; i < n; i++) {
if (record[i]) {
return i;
}
}
return -1;
}
public int firstUniqChar(String s) {
int freq [] = new int[26];
for(int i = 0; i < s.length(); i ++)
freq [s.charAt(i) - 'a'] ++;
for(int i = 0; i < s.length(); i ++)
if(freq [s.charAt(i) - 'a'] == 1)
return i;
return -1;
}
//二刷,java8版
public int firstUniqChar(String s) {
if (s == null || s.length() == 0) {
return -1;
}
Map<Character, Integer> map = new HashMap<>();
for (int i = 0; i < s.length(); i++) {
char cur = s.charAt(i);
map.put(cur, map.getOrDefault(cur, 0) + 1);
}
for (int i = 0; i < s.length(); i++) {
if (map.get(s.charAt(i)) == 1) {
return i;
}
}
return -1;
}