题目:输入几个非空字符串。输出第一个只出现一次的字符,如果不存在输出-1。
#include<iostream>
#include <string>
#include<cstring>
using namespace std;
int main()
{
char str1[500]={0};
while (cin >> str1) {
char a[500]={0};
int len = strlen(str1);
for (int i = 0; i < len; i++)
{
a[str1[i]-'a']++; //str1[i]-'a'的ascii值出现过即+1
}
for (int k = 0; k < len; k++)
{
if (a[str1[k]-'a'] == 1)
{
cout << str1[k] << endl;
break;
}
if(k==(len-1))
cout << -1 << endl;
}
}
return 0;
}
自己理解:只要字符串里一个字符出现过,自定义的数组的值+1,最后判断数组中第一个为1的字符,并输出即可
参考:https://www.nowcoder.com/ta/huawei