题目
Given a string, find the first non-repeating character in it and return it's index. If it doesn't exist, return -1.
Examples:
s = "leetcode" return 0. s = "loveleetcode", return 2.
Note: You may assume the string contain only lowercase letters.
分析
1 先s.tochararray 的效率要比 s.charat[idx]要高一些
2 ASCII 码处理会更好一些,先构造一个26大小的数组,索引对应的是字母,值对应的是出现的次数
第二次遍历值为1的值即可
3 拓展 有效的字母异位词也可以这样处理 先统计,再减少,再遍历是否有不为0的值
代码
public int firstUniqChar(String s) {
int[] freq = new int[26];
char[] array = s.toCharArray();
for(char c : array){
freq[c - 'a']++;
}
for(int i = 0; i < array.length; i++){
if(freq[array[i] - 'a'] == 1) return i;
}
return -1;
}