找出给定字符串中最后一个只出现一次的字符,如字符串abbcddefgghh,输出结果为f。
借助C++ map容器实现,主要思路是:遍历字符串中每个字符元素,通过map容器记录每个字符出现的次数,然后在map容器中遍历找到最后一个字符出现次数为1的那个字符。
#include <iostream>
#include <string>
#include <unordered_map>
using namespace std;
int main()
{
string str;
getline(cin, str);
unordered_map<char, int> mp;
string::iterator it;
for (it=str.begin(); it!=str.end(); it++)
{
mp[*it]++;
}
char ch=0;
for (int i=str.length(); i>=0; i--)
{
if (mp[str[i]]==1)
{
ch=str[i];
break;
}
}
if (ch==0)
{
cout<<"NULL"<<endl;
}
else
{
cout<<ch<<endl;
}
system("pause");
return 0;
}
注意:遍历map容器的时候最好反向遍历,找到第一个字符元素就行了,正向遍历通不过测试,没搞清楚什么原因。