给定一个字符串,找到它的第一个不重复的字符,并返回它的索引。如果不存在,则返回 -1。
示例:
s = “leetcode”
返回 0
思路:
建立一个哈希表,存放字符串每个字符出现的次数。然后再遍历该字符串,如果该字符出现的次数为1返回即可,不存在返回-1。
class Solution {
public:
int firstUniqChar(string s) {
unordered_map<char,int> map;
for(auto c:s){
++map[c];
}
for(int i=0;i<s.size();++i){
if(map[s[i]]==1)
return i;
}
return -1;
}
};
也可以使用数组速度快一些。
class Solution {
public:
int firstUniqChar(string s) {
int hash[26]={0};
for(auto n:s){
hash[n-'a']++;
}
for(int i=0;i<s.size();++i){
if(hash[s[i]-'a']==1)
return i;
}
return -1;
}
};