题目描述
找出字符串中第一个只出现一次的字符
输入描述:
输入一个非空字符串
输出描述:
输出第一个只出现一次的字符,如果不存在输出-1
示例1
输入
asdfasdfo
输出
o
代码:
//第五十七题 找出字符串中第一个只出现一次的字符(题面已经更新)
#include<iostream>
#include<string>
using namespace std;
int main()
{
string str;
while (cin >> str)
{
int a[26]{ 0 };
int aP[26]{ 0 };
int A[26]{ 0 };
int AP[26]{ 0 };
size_t sLength = str.length();
for (int i = 0; i < sLength; i++)
{
if (isupper(str[i]))
{
if (A[str[i] - 'A'] == 0)
AP[str[i] - 'A'] = i;
A[str[i] - 'A']++;
}
else
{
if (a[str[i] - 'a'] == 0)
aP[str[i] - 'a'] = i;
a[str[i] - 'a']++;
}
}
int mun = 1;
int iMinId = 0;
int iMinPosition = 1000;
for (int i = 0; i < 26; i++)
{
if (A[i] == 1)
{
if (iMinPosition > AP[i])
{
iMinPosition = AP[i];
iMinId = i;
}
mun = 0;
}
if (a[i] == 1)
{
if (iMinPosition > aP[i])
{
iMinPosition = aP[i];
iMinId = i;
}
mun = 0;
}
}
if (mun)
cout << -1 << endl;
else
{
if (aP[iMinId] == iMinPosition)
{
char temp = iMinId+ 'a';
cout << temp << endl;
}
else
{
char temp = iMinId + 'A';
cout << temp << endl;
}
}
}
return 0;
}