Given a string, find the first non-repeating character in it and return it’s index. If it doesn’t exist, return -1.
Examples:
s = “leetcode”
return 0.
s = “loveleetcode”,
return 2.Note: You may assume the string contain only lowercase letters.
限定字母范围为26个小写字母,可以按照哈希表的思想把字符串S中每个字母的出现频率进行统计,再找到s的字符串顺序找到第一个频率为1的字母即可。
class Solution {
public:
int firstUniqChar(string s) {
int count[26]={0};
if(s.empty()) return -1;
for(int i=0;i<s.size();i++){
count[s[i]-'a']++;
}
for(int i=0;i<s.size();i++){
if(count[s[i]-'a']==1)
return i;
}
return -1;
}
};