找出字符串中只出现一次的字符(C++)
Posted L_add
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了找出字符串中只出现一次的字符(C++)相关的知识,希望对你有一定的参考价值。
找出字符串中只出现一次的字符
题目来源:牛客
思路:
-
- 对字符串的每一个字符进行hash映射
-
- 按顺序检测每一个字符是否只出现一次
#include<iostream>
#include<string>
#include<list>
using namespace std;
int Hash(int key)
{
return key - 'a';
}
int FirstTimeChar(string &str)
{
int hashtable[26] = {0};
//对字符串的每一个字符进行hash映射
for(int i=0; i<str.size(); ++i)
{
int index = Hash(str[i]);
hashtable[index]++;
}
//按顺序检测每一个字符是否只出现一次
for(int i=0; i<str.size(); ++i)
{
int index = Hash(str[i]);
if(hashtable[index] == 1)
return str[i];
}
return -1;
}
int main()
{
string str;
while(getline(cin, str))
{
char res = FirstTimeChar(str);
if(res == -1)
cout<<-1<<endl;
else
cout<<res<<endl;
}
return 0;
}
以上是关于找出字符串中只出现一次的字符(C++)的主要内容,如果未能解决你的问题,请参考以下文章