找第一个只出现一次的字符

GitHub跳转原题关系图返回列表

用 Counter 统计字符频率后按原顺序找第一个频率为一的字符。

OJ: noi_openjudge

题目 ID: ch0107-02

难度:入门

标签:字符串计数python

日期: 2026-07-30 23:01

题意

找出小写字符串中第一个只出现一次的字符,没有则输出 no

思路

先用 Counter 统计频率,再按原字符串顺序寻找频率为 11 的字符,才能保证“第一个”。next(..., "no") 在找不到时给出默认结果。

代码

Python代码

python
from collections import Counter

text = input().strip()
frequencies = Counter(text)
print(next((character for character in text if frequencies[character] == 1), "no"))

C++代码

cpp
#include <cstdio>
#include <cstring>

char str[100005];
int cnt[500] = {0};

int main(){
    scanf("%s",&str[1]);
    int len = strlen(&str[1]);
    int i,j;
    for (i=1;i<=len;i++){
        cnt[ str[i] ]++;
    }
    for (i=1;i<=len;i++){
        if( cnt[ str[i] ] == 1){
            printf("%c\n",str[i]);
            return 0;
        }
    }
    printf("no");
    return 0;
}

复杂度

时间复杂度为 O(n)O(n),频次表使用 O(n)O(n) 空间。

总结

先统计、再按原顺序扫描,是“第一个满足频率条件元素”的通用做法。