给定一个字符串 s ,找到 它的第一个不重复的字符,并返回它的索引 。如果不存在,则返回 -1 。
解答一:利用C++的STL属性,直接查找字符然后返回索引值。
class Solution {
public:
int firstUniqChar(string s) {
for(int i = 0; i < s.size(); i++){
if(s.rfind(s[i]) == i && s.find(s[i]) == i) return i;
}
return -1;
}
};
解答二:利用哈希表记录每个字符出现的次数,第二次遍历的时候,返回出现次数为1的字符索引。需要额外的内存空间。
class Solution {
public:
int firstUniqChar(string s) {
map<char, int> count;
for(char ch : s){
++count[ch];
}
for(int i = 0; i < s.size(); i++){
if(count[s[i]] == 1) return i;
}
return -1;
}
};