题目描述
在一个字符串(1<=字符串长度<=10000,全部由字母组成)中找到第一个只出现一次的字符的位置。若为空串,返回-1。位置索引从0开始
分析:就是建立一个哈希表,把每个字符出现的次数求出来,第二次遍历找到第一个出现次数为1的字符。
代码:
class Solution {
public:
int FirstNotRepeatingChar(string str) {
int n=str.size();
if(n==0) return -1;
int count[256]={0};
int i=0;
while(str[i]!='\0'){
count[str[i]]++;
i++;
}
i=0;
while(str[i]!='\0'){
if(count[str[i]]==1){
return i;
}
i++;
}
return -1;
}
};