可以使用暴力求解:
class Solution {
public:
int FirstNotRepeatingChar(string str) {
for(int i =0; i < str.length(); ++i){
bool hasSeem = false;
for(int j = 0; j < str.length(); ++j){
if(i !=j && str[i] == str[j]){
hasSeem = true;
break;
}
}
if(!hasSeem) return i;
}
return -1;
}
}; 使用 map 也行:
class Solution {
public:
int FirstNotRepeatingChar(string str) {
map<char, int> data;
for(int i =0; i < str.length(); ++i){
++data[str[i]];
}
for(int i = 0; i < str.length(); ++i){
if(data[str[i]] == 1) return i;
}
return -1;
}
}; 或者是使用 hash
class Solution {
public:
int FirstNotRepeatingChar(string str) {
unordered_map<char, int> data;
for(int i =0; i < str.length(); ++i){
++data[str[i]];
}
for(int i = 0; i < str.length(); ++i){
if(data[str[i]] == 1) return i;
}
return -1;
}
}; 
京公网安备 11010502036488号