给定一个字符串,找到它的第一个不重复的字符,并返回它的索引。如果不存在,则返回 -1。
案例:
s = "leetcode"
返回 0.
s = "loveleetcode",
返回 2.
注意事项:您可以假定该字符串只包含小写字母。
java代码实现:
class Solution {
public int firstUniqChar(String s) {
//创建一个哈希表,key存储出现的字符,value统计出现频率
HashMap<Character, Integer> map = new HashMap<>();
char[] chars = s.toCharArray();
for (char 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;
}
}
网友评论