字符串中第一个不重复字符
map版本
#include<iostream>
#include<string>
#include<map>
using namespace std;
int main() {
string str;
map<char, int> m;
cin >> str;
for (int i = 0; i < str.length(); i++) {
if (!m.count(str[i])) {
m[str[i]] = 1;
}
else
{
m[str[i]]++;
}
}
map<char, int>::iterator it;
for (it = m.begin(); it != m.end(); it++) {
cout << it->first << ":" << it->second << endl;
}
for (int i = 0; i < str.length(); i++) {
//cout << str[i] << ":" << m[str[i]] << endl;
if (m[str[i]] == 1) {
cout << str[i] << endl;
break;
}
}
return 0;
}
本文介绍了一种使用C++ map容器寻找字符串中第一个不重复字符的方法。通过遍历字符串并利用map记录每个字符出现的次数,再遍历字符串找到第一个出现次数为1的字符,实现了高效查找。
231

被折叠的 条评论
为什么被折叠?



