- 字符串中的第一个唯一字符
给定一个字符串,找到它的第一个不重复的字符,并返回它的索引。如果不存在,则返回 -1。
提示:你可以假定该字符串只包含小写字母。
示例:
s = “leetcode”
返回 0
s = “loveleetcode”
返回 2
过程解析:
class Solution {
public int firstUniqChar(String s) {
//用HashMap求解,遍历字符串,将字符加入哈希表中,再遍历字符串,判断存储的次数是否为1,若为1,则返回索引
HashMap<Character,Integer> hm = new HashMap<Character,Integer>();
for(int i=0;i<s.length();i++){
//先遍历字符串,存储到哈希表中
int num=hm.getOrDefault(s.charAt(i),0)+1;
hm.put(s.charAt(i),num);
}
for(int i=0;i<s.length();i++){
//判断存储的字符是否重复
if(hm.get(s.charAt(i))==1){
return i;
}
}
return -1;
}
}
结果:
执行用时:28 ms, 在所有 Java 提交中击败了27.08%的用户
内存消耗:39.1 MB, 在所有 Java 提交中击败了19.11%的用户
通过测试用例:104 / 104