输入描述:
输入一个非空字符串
- 1
输出描述:
输出第一个只出现一次的字符,如果不存在输出-1
- 1
示例1
输入
asdfasdfo
输出
o
用空间换时间的方法,遍历一次即可
#include<iostream>
#include<string>
using namespace std;
void find(string a)
{
char s = NULL;
int i = 0;
int p[256] = { 0 };
for (i = 0; i<a.size(); i++)
{
p[a[i]]++;
}
for (i = 0; i<a.size(); i++)
{
if(p[a[i]]==1)
{
s=a[i];
break;
}
}
if (s == NULL)
{
cout << -1 << endl;
}
else
{
cout << s << endl;
}
}
int main()
{
string a;
while (cin >> a)
{
find(a);
}
}

本文介绍了一种高效的算法,用于从字符串中找到第一个仅出现一次的字符。通过使用额外的空间来存储每个字符的出现次数,该算法能够在遍历字符串一次后立即找出目标字符,如果不存在则返回特定标识。

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



