题目描述
给定一个字符串,找到它的第一个不重复的字符,并返回它的索引。如果不存在,则返回 -1。
示例:
s = “leetcode”
返回 0
s = “loveleetcode”
返回 2
提示:你可以假定该字符串只包含小写字母。
分析
1.定义HashMap,其中键是字符,值是字符出现的次数;
2.定义List,把HashMap中值=1的字符放入List;
3.比较List中字符的索引,取最小值
代码
class Solution {
public int firstUniqChar(String s) {
HashMap<Character, Integer> map = new HashMap<>();
for(Character c:s.toCharArray()) {
int count=1;
if(map.containsKey(c)) {
map.put(c, map.get(c)+1);
continue;
}
map.put(c, count);
}
List<Character> list = new ArrayList<>();
for(Character c2 : map.keySet()) {
if(map.get(c2)==1) {
list.add(c2);
}
}
if(list.size()==0) {
return -1;
}else {
int min = Integer.MAX_VALUE;
for(Character c3:list) {
min=s.indexOf(c3)<min?s.indexOf(c3):min;
}
return min;
}
}
}
优化
List是多余的。
只需要遍历字符串,如果当前索引下的字符对应的HashMap的值=1,就返回当前索引,结束即可。
class Solution {
public int firstUniqChar(String s) {
HashMap<Character, Integer> map = new HashMap<>();
for(Character c:s.toCharArray()) {
int count=1;
if(map.containsKey(c)) {
map.put(c, map.get(c)+1);
continue;
}
map.put(c, count);
}
for(int i=0;i<s.length();i++) {
if(map.get(s.charAt(i))==1) {
return i;
}
}
return -1;
}
}