注意:

字符串的第一个字符存在下标为0处

字符出现次数的统计方法,定义一个数组ch[26]

下标分别对应‘a’..'z'

方法char c='a';

c-96=1,因为此时c的ASCII码参与运算

 

读完再扫描,注意字符出现的次数为0的应该去掉

#include<cstdio>
#include<cstring>
char s[200],ch[100]={0};
int main(){
    scanf("%s",s);
    int len=strlen(s);
    int maxn=-1,minn=500;
    for (int i=0;i<=len-1;i++){
        int t=s[i]-96;
        ch[t]++;
       }
    for (int i=1;i<=26;i++){
        if (ch[i]>maxn) maxn=ch[i];
        if (ch[i]!=0&&ch[i]<minn) minn=ch[i];
    }
    int i,n=maxn-minn;
    if (n>=2){
        for (i=2;i<=n-1&&n%i!=0;i++);
        if (n==2||i==n) printf("Lucky Word\n%d\n",n); 
        else printf("No Answer\n0\n");       
    }  
    else printf("No Answer\n0\n");
    return 0;
}
View Code

如果只出现一个字符的情况,单独考虑

#include<cstdio>
#include<cstring>
char s[200],ch[100]={0};
int main(){
    scanf("%s",s);
    int len=strlen(s);
    int maxn=-1,minn=500;
    for (int i=0;i<=len-1;i++){
        int t=s[i]-96;
        ch[t]++;
       }
       int p=0;
    for (int i=1;i<=26;i++){
        if (ch[i]>maxn&&ch[i]>0) maxn=ch[i];
        if (ch[i]>0&&ch[i]<minn) {minn=ch[i];p++;}
    }
    int i,n;
    printf("%d %d  \n",minn,maxn);
    if (minn==maxn&&p==1) n=maxn;//如果只出现一个字符的情况,单独考虑 
    else n=maxn-minn;
    printf("%d %d  \n",minn,maxn);
    if (n>=2){
        int bo=0;
        for (i=2;i<=n-1;i++)
            if (n%i==0){
                bo=1;break;
            }
        if (!bo) printf("Lucky Word\n%d\n",n); 
        else printf("No Answer\n0\n");       
    }  
    else printf("No Answer\n0\n");
    return 0;
}
View Code