一.问题描述
-
给定一个字符串,找到它的第一个不重复的字符,并返回它的索引。如果不存在,则返回 -1。
-
示例:
-
s = “leetcode”
-
返回 0
-
s = “loveleetcode”
-
返回 2
二.示例代码
public static void main(String[] args) {
String s = "leetcode";
int result = firstUniqueChar2(s);
System.out.println(result);
}
private static int firstUniqueChar(String s) {
for (int i = 0; i < s.length(); i++) {
boolean noRepeat = true;
for (int j = 0; j < s.length(); j++) {
if (i == j) {
continue;
}
if (s.charAt(i) == s.charAt(j)) {
noRepeat = false;
break;
}
}
if (noRepeat) {
return i;
}
}
return -1;
}
public static int firstUniqueChar2(String s) {
Map<Character, Integer> frequency = new HashMap<>();
for (int i = 0; i < s.length(); ++i) {
char ch = s.charAt(i);
frequency.put(ch, frequency.getOrDefault(ch, 0) + 1);
}
for (int i = 0; i < s.length(); ++i) {
if (frequency.get(s.charAt(i)) == 1) {
return i;
}
}
return -1;
}