题目描述
- 在字符串中找出第一个只出现一次的字符
- 如,输入
"abaccdeff"
,则输出 b
题目解读
代码
#include<iostream>
#include<map>
using namespace std;
class Solution {
public:
int FirstNotRepeatingChar(string str) {
int len = str.size();
map<char, int> mp;
for (int i = 0; i < len; ++i){
mp[str[i]] ++;
}
for (int i = 0; i < len; ++i){
if(mp[str[i]] == 1){
return i;
}
}
return -1;
}
};
int main(){
Solution ss;
string str = "abaccdeff";
cout<<ss.FirstNotRepeatingChar(str);
}
#include<iostream>
using namespace std;
class Solution {
public:
int FirstNotRepeatingChar(string str) {
int len = str.size();
int *mp = new int[256]; // 字符共计256种
for (int i = 0; i < len; ++i){
mp[str[i]] ++;
}
for (int i = 0; i < len; ++i){
if(mp[str[i]] == 1){
return i;
}
}
return -1;
}
};
int main(){
Solution ss;
string str = "abaccdeff";
cout<<ss.FirstNotRepeatingChar(str);
}
总结展望