文章

454

粉丝

0

获赞

1

访问

10.3k

头像
统计字符数 题解(四语言 AC 代码)
P5293 北京大学2025年机试题
发布于 2026年11月
阅读数 39

题意

统计 a–z 组成的字符串中出现次数最多的字符及其次数;并列时取 ASCII 码更小的。

思路

  • 开 26 个计数器扫一遍字符串。

  • 从 a 到 z 顺序扫描取最大值,严格大于才更新,天然满足并列取小者。

复杂度

O(L + 26)。

参考代码(C / C++ / Java / Python)

C:

#include <stdio.h>
int main(){
    char s[1005]; int i,cnt[26]={0},mx=-1,mc=-1;
    if(scanf("%1000s",s)!=1) return 0;
    for(i=0;s[i];i++) cnt[s[i]-'a']++;
    for(i=0;i<26;i++) if(cnt[i]>mx){ mx=cnt[i]; mc=i; }
    printf("%c %d\n",'a'+mc,mx);
    return 0;
}

C++:

#include <stdio.h>
int main(){
    char s[1005]; int i,cnt[26]={0},mx=-1,mc=-1;
    if(scanf("%1000s",s)!=1) return 0;
    for(i=0;s[i];i++) cnt[s[i]-'a']++;
    for(i=0;i<26;i++) if(cnt[i]>mx){ mx=cnt[i]; mc=i; }
    printf("%c %d\n",'a'+mc,mx);
    return 0;
}

Java:

import java.io.*;
import java.util.*;

public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringBuilder sb = new StringBuilder();
        ArrayList<String> tk...
登录查看完整内容


登录后发布评论

暂无评论,来抢沙发