题目描述
在一个字符串(0<=字符串长度<=10000,全部由字母组成)中找到第一个只出现一次的字符,并返回它的位置, 如果没有则返回 -1(需要区分大小写).(从0开始计数)
题解
基本思路就是哈希方法,遍历一遍字符串,统计每个字符出现的次数。然后再遍历一遍字符串,找出答案。
class Solution {
public:
int FirstNotRepeatingChar(string str) {
if(str.length() == 0)
return -1;
int count[256] = {0};
for(int i=0; i<str.length(); i++){
count[str[i]] += 1;
}
for(int i=0; i<str.length(); i++){
if(count[str[i]] == 1)
return i;
}
return -1;
}
};