题目地址:
https://www.acwing.com/problem/content/774/
给你一个只包含小写字母的字符串
s
s
s。请你判断是否存在只在字符串中出现过一次的字符。如果存在,则输出满足条件的字符中位置最靠前的那个。如果没有,输出no
。
输入格式:
共一行,包含一个由小写字母构成的字符串。数据保证字符串的长度不超过
100000
100000
100000。
输出格式:
输出满足条件的第一个字符。如果没有,则输出no
。
代码如下:
#include <iostream>
using namespace std;
int main() {
string s;
cin >> s;
int cnt[26] = {0};
for (char ch : s) cnt[ch - 'a']++;
bool found = false;
for (char ch : s)
if (cnt[ch - 'a'] == 1) {
found = true, printf("%c\n", ch);
break;
}
if (!found) puts("no");
return 0;
}
时间复杂度 O ( l s ) O(l_s) O(ls),空间 O ( 1 ) O(1) O(1)。