给定一个字符串 s ,找到 它的第一个不重复的字符,并返回它的索引 。如果不存在,则返回 -1 。
示例1:
输入: s = "leetcode"
输出: 0
示例2:
输入: s = "loveleetcode"
输出: 2
示例3:
输入: s = "aabb"
输出: -1
解题思路:
1.首先遍历字符串s,将s中出现的字符的次数存储在一个数组中。
2.接着再次遍历s,如果出现的次数等于1,则返回索引
Java代码如下:
class Solution {
public int firstUniqChar(String s) {
char[] chars = s.toCharArray();
int[] count = new int[26];
for(char c:chars){
count[c-'a']++;
}
for(int i=0;i<chars.length;i++){
if(count[chars[i]-'a']==1)
return i;
}
return -1;
}
}