C语言求思路指导

题目:输入一串字符,输出出现次数最多的那个字符
输入:

第一行是测试数据的组数n,接下来的每组测试数据占一行,每行数据不超过1000个字符且非空。

字符串里只含小写字母。
输出:
每组数据对应输出一行,包括出现次数最多的字符和该字符出现的次数,中间是一个空格。如果有多个字符出现的次数相同且最多,那么输出ASCII码最小的那一个字符。
Sample Input

2
abbccc
adfadffasdf

Sample Output

c
3
f
4
经过思考以后我做到了这里

拜托各位指出错漏点,本人新手错漏较多希望大家不吝赐教!

#include <stdio.h>
void main( )
{
    int i, j, max, n, s[26];
    char str[100][1000], ch;
    scanf("%d", &n);
    for(i = 0; i < n; i++)
    {
        fflush(stdin);
        gets(str[i]);
    }
    for(i = 0; i < n; i++)
    {
        for(j = 0; j < 26; j++) s[j] = 0;
        for(max = 0, j = 0; str[i][j]; j++)
        {
            ch = str[i][j] - 'a';
            s[ch]++;
            if(s[ch] > s[max]) max = ch;
        }
        printf("%c\n%d\n", max + 'a', s[max]);
    }
}

运行结果

追问

谢谢你的回答,能不能拜托你帮我看看我的那个程序,指出错漏点!

追答

你的程序的问题是很多的,你自己对比一下,我按你的思路给出如下程序,你自己比较一下
#include
#include
void main( ) {
char str[1001], letter, *N;
int n, i, j, max, maxindex, ch[26], *p;
scanf("%d", &n);
while(n ch[maxindex]) {
maxindex = j;
max = ch[j];
}
}
letter = maxindex + 'a';
*(p + i) = max;
*(N + i) = letter;
}
for(i = 0; i < n; i++) {
printf("%c\n", *(N + i));
printf("%d\n", *(p + i));
}
}

追问

你的程序中的while(n < 1) scanf("%d", &n);是什么意思啊?
还有你程序中的if(p == NULL) return;和我定义的那个动态数组

有什么不同啊?解答完这个我就明白了!

追答

1 你的scanf( )语句放while逻辑判断里,那又是什么呢?最好不要将scanf( )作为逻辑判断条件。while(n < 1) scanf("%d", &n); 是要求测试用例的个数不小于1啊,如果输入的是小于1则重新输入啊。
2 和你的没有什么很大的本质不同,只是为了可读性,不让if的逻辑判断部分太长而使得难懂。return是退出函数,exit(1)是终止程序。退出主函数实际上也就是终止程序,但如果能用return的地方则最好不要用exit(具体是为什么,你现在还不需要知道,说多了你可能会不太懂)。

追问

scanf( )语句放while逻辑判断是为了可以多次输入测试用例啊!谢谢你的回答!

温馨提示:答案为网友推荐,仅供参考
第1个回答  2014-03-25
#include<stdio.h>
#include<string.h>
main()
{
int x,i,max,q;
char a[1011];
scanf("%d",&x);
getchar();
while(x--)
{
int s[26]={0};
gets(a);
for(i=strlen(a)-1;i>=0;i--)
s[a[i]-97]++;
max=0;
for(i=0;i<26;i++)
if(max<s[i]) max=s[i],q=i;
printf("%c\n",q+97);
}
}

第2个回答  2014-03-25
# include <stdio.h>
# include <string.h>

int main(void)
{
    int n;
    char str[1001];
    int hash[26];
    int i;

    scanf("%d", &n);
    getchar();
    while(n--)
    {
        memset(hash, 0, sizeof(hash));
        scanf("%s", str);

        for(i = 0; str[i]; ++i)
        {
            hash[str[i]-'a']++;
        }
        int max = hash[0];
        int index = 0;
        for(i = 1; i < 26; ++i)
        {
            if(hash[i]>max)
            {
                max = hash[i];
                index = i;
            }
        }
        printf("%c %d\n", index+'a', max);
    }
    return 0;
}

相似回答