题目
给定一个字符串,找到它的第一个不重复的字符,并返回它的索引。如果不存在,则返回 -1。
案例:
s = "leetcode"
返回 0.
s = "loveleetcode",
返回 2.
注意事项:您可以假定该字符串只包含小写字母。
解决方法
方法1:
class Solution {
public int firstUniqChar(String s) {
//fast
int n = s.length();
for(int i = 'a'; i<='z';i++){
int start = s.indexOf(i);
int end = s.lastIndexOf(i);
if(start == end && start != -1){
n = Math.min(start, n);
}
}
if(n==s.length()){
return -1;
}else{
return n;
}
}
}
方法2:
class Solution {
public int firstUniqChar(String s) {
char[] chars = s.toCharArray();
HashMap<Character,Integer> map = new HashMap<>();
for (char aChar : chars) {
map.put(aChar,map.getOrDefault(aChar,0)+1);
}
for (int i = 0; i < chars.length; i++) {
if (map.get(chars[i]) == 1) {
return i;
}
}
return -1;
}
}