LeetCode Link
public int firstUniqChar(String s) {
LinkedHashMap<Character, Integer> uniqMap = new LinkedHashMap<>();
Set<Character> dupSet = new HashSet<>();
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (dupSet.contains(c)) {
continue;
} else if (uniqMap.containsKey(c)) {
uniqMap.remove(c);
dupSet.add(c);
} else {
uniqMap.put(c, i);
}
}
Iterator<Map.Entry<Character, Integer>> iter = uniqMap.entrySet().iterator();
return iter.hasNext() ? iter.next().getValue() : -1;
}
public int firstUniqChar(String s) {
LinkedHashMap<Character, Integer> map = new LinkedHashMap<>();
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (!map.containsKey(c)) {
map.put(c, i);
} else {
map.put(c, -1);
}
}
Iterator<Map.Entry<Character, Integer>> iter = map.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry<Character, Integer> entry = iter.next();
if (entry.getValue() >= 0) {
return entry.getValue();
}
}
return -1;
}
网友评论