在一个字符串(0<=字符串长度<=10000,全部由字母组成)中找到第一个只出现一次的字符,并返回它的位置, 如果没有则返回 -1(需要区分大小写).(从0开始计数)
我的代码:
class Solution {
public:
int FirstNotRepeatingChar(string str) {
if(str.size() == 0) return -1;
int count[58];
int visited[58];
int index = INT_MAX;
for(int i = 0; i < 58; i++) {
count[i] = 0;
visited[i] = -1;
}
for(int i = 0; i < str.size(); i++) {
if(str[i] >= 'a' && str[i] <= 'z') {
if(visited[str[i]-'a'] == -1)
visited[str[i]-'a'] = i;
count[str[i]-'a']++;}
else {count[str[i]-'A'+26]++;
if(visited[str[i]-'A'+26] == -1)
visited[str[i]-'A'+26] = i;}
}
for(int i = 0; i < 58; i++){
if(count[i] == 1) {
if(visited[i] != -1 && visited[i] < index) index = visited[i];
}
}
return index;
}
};
利用map
class Solution {
public:
int FirstNotRepeatingChar(string str) {
map<char, int> mp;
for(int i = 0; i < str.size(); ++i)
mp[str[i]]++;
for(int i = 0; i < str.size(); ++i){
if(mp[str[i]]==1)
return i;
}
return -1;
}
};