给定一个字符串,找到它的第一个不重复的字符,并返回它的索引。如果不存在,则返回 -1。
class Solution {
public int firstUniqChar(String s) {
//统计字符串中出现的字母个数
//下标为字母,内容为出现的次数
int[] arr = new int[26];
for (char c : s.toCharArray()) {
arr[c - 97]++;
}
//遍历字符串的所有字符,如果在arr数组里找,如果为1就返回下标
char[] ch = s.toCharArray();
for (int i = 0; i < ch.length; i++) {
if (arr[ch[i] - 97] == 1) {
return i;
}
}
return -1;
}
}