题目描述
给定一个字符串,找到它的第一个不重复的字符,并返回它的索引。如果不存在,则返回 -1。
- 示例:
- s = “leetcode”
- 返回 0
- s = “loveleetcode”
- 返回 2
题解
1.对字符串进行两次遍历。
2.在第一次遍历时,使用哈希映射统计出字符串中每个字符出现的次数。
3.在第二次遍历时,只要遍历到了一个只出现一次的字符,那么就返回它的索引,否则在遍历结束后返回 -1。
class Solution {
public:
int firstUniqChar(string s) {
int arr[26]={0};
for(auto ch : s)
arr[ch-'a']++;
for(size_t i=0;i<s.size();++i){
if(arr[s[i]-'a']==1)
return i;
}
return -1;
}
};