给定一个字符串,找到它的第一个不重复的字符,并返回它的索引。如果不存在,则返回 -1。
案例:
注意事项:您可以假定该字符串只包含小写字母。
解法1:
两次遍历,第一次遍历先把字符和出现的次数存入map里, 第二次遍历取出map中次数为1的第一个字符;
class Solution {
public int firstUniqChar(String s) {
char[] chars = s.toCharArray();
Map<Character, Integer> map = new HashMap();
for(Character c:chars) {
//频率统计
map.put(c, map.getOrDefault(c, 0) + 1);
}
for (int i = 0; i < chars.length; i++) {
if(map.get(chars[i])==1) return i;//找到词频为1的字母(只出现一次)返回其索引
}
return -1;
}
}
解法2:
利用 Java 字符串indexOf函数实现
class Solution {
public int firstUniqChar(String s) {
int res = s.length();
for (int i = 'a'; i <= 'z'; i++) {
int firstIndex = s.indexOf((char)i);
if (firstIndex == -1) continue;
int lastIndex = s.lastIndexOf((char)i);
if (firstIndex == lastIndex) {//两次索引值相同则证明该字母只出现一次
res = Math.min(firstIndex, res);//res 为只出现一次的字母中索引值最小的
}
}
return res == s.length() ? -1 : res;
}
}