UVA409 - Excuses, Excuses!

问题描述

n个关键字,m个句子,输出句子中存在最多关键字的句子(如果关键字数量相同,则按顺序输出)。

思路

将所需的字符全部转换成小写,用一个数组g来存储一个单词,然后判断是否为英文字母,如果是,则存储,否则一个单词结束,然后逐一比较关键字。
PS:同样的思路WA多次后才发现,记录关键字的数组没有初始化。多组测试数据时,应注意对数组及变量进行初始化。

代码

#include <iostream>
#include <cstring>
#include <cctype>
#include <cstdio>
using namespace std;
const int N =100;
char word[N][N];
int n,m;
int main()
{
    char s[N][N],str[N][N],g[N];;
    int ans[N];
    int i,j,maxn,kase=1;
    while(scanf("%d%d",&n,&m)!=EOF)
    {
        memset(ans,0,sizeof(ans)); //此处未初始化导致WA多次
        getchar();
        maxn=0;
        for(i=0;i<n;i++)
        {
            gets(word[i]);
            for(j=0;j<strlen(word[i]);j++)
            {
                if(isalpha(word[i][j]))
                    word[i][j]=tolower(word[i][j]);
            }
        }
        for(i=0;i<m;i++)
        {
            gets(s[i]);
            strcpy(str[i],s[i]);
            for(j=0;j<strlen(str[i]);j++)
            {
                if(isalpha(str[i][j]))
                    str[i][j]=tolower(str[i][j]);
            }
            int len=strlen(str[i]);
            int line=0;
            for(j=0;j<len;j++)
            {
                if(isalpha(str[i][j]))
                    g[line++]=str[i][j];
                else
                {
                    g[line]='\0';
                    line=0;
                    for(int k=0;k<n;k++)
                    {
                        if(strcmp(g,word[k])==0)
                         {
                             ans[i]++;
                             break;
                         }
                    }
                }
            }
        }
        printf("Excuse Set #%d\n",kase++);
        for(i=0;i<m;i++)
        {
            //cout<<ans[i]<<endl;
            if(ans[i]>=maxn)
                maxn=ans[i];
        }
        for(i=0;i<m;i++)
        {
            if(ans[i]==maxn)
                printf("%s\n",s[i]);
        }
        printf("\n");
    }
    return 0;
}
发布了64 篇原创文章 · 获赞 3 · 访问量 6243

猜你喜欢

转载自blog.csdn.net/qazsatan/article/details/52429726
今日推荐