第一个只出现一次的字符位置
题目描述
在一个字符串(0<=字符串长度<=10000,全部由字母组成)中找到第一个只出现一次的字符,并返回它的位置, 如果没有则返回 -1(需要区分大小写).
解题思路
- 开一个标记数组,扫描一遍字符串,记录每个字符出现的次数,出现一次+1
- 再扫描一遍字符串(注意,还是扫描字符串,而不是标记数组),如果标记数组中出现次数为1,就是第一次只出现一次的字符,返回在字符串中的位置,否则遍历完没有出现一次的字符,返回-1
class Solution {
public:
int FirstNotRepeatingChar(string str) {
if(str.empty()) return -1;
int len=str.length();
int book[128]={0};
for(int i=0;i<len;i++){
int idx = str[i]-'A';
book[idx]++;
}
for(int i=0;i<len;i++){
int idx = str[i]-'A';
if(book[idx]==1)
return i;
}
return -1;
}
};