文章
454
粉丝
0
获赞
1
访问
10.3k
统计 a–z 组成的字符串中出现次数最多的字符及其次数;并列时取 ASCII 码更小的。
开 26 个计数器扫一遍字符串。
从 a 到 z 顺序扫描取最大值,严格大于才更新,天然满足并列取小者。
O(L + 26)。
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...
登录后发布评论
暂无评论,来抢沙发