题解 | #找出字符串中第一个只出现一次的字符#
找出字符串中第一个只出现一次的字符
https://www.nowcoder.com/practice/e896d0f82f1246a3aa7b232ce38029d4
#include <iostream>
#include<string>
using namespace std;
//找出字符串中第一个只出现一次的字符
int main()
{
string str;
cin>>str;
int flag[1001]={0}; //标记所访问字符是否已经访问过
int first=1,second=1;
for(int i=0;i<str.size();i++){
first=1;
if(flag[i]==0){ //如果该字符之前没有被访问过,那么则遍历其后的所有字符
for(int j=i+1;j<str.size();j++){
if(str[i]==str[j]){
first=0;
flag[j]=1;
}
}
}
if(first==1&&flag[i]==0){ //输出字符串中第一个只出现一次的字符,因为第一个访问的字符不做标记
cout<<str[i];
second=0;
break;
}
}
if(second==1) cout<<-1; //如果从未出现过,输出-1
return 0;
}
查看12道真题和解析