字符串匹配

来源:互联网 发布:linux启动服务的命令 编辑:程序博客网 时间:2024/06/05 20:28

链接:http://acm.hrbust.edu.cn/index.php?m=ProblemSet&a=showProblem&problem_id=1109


字符串匹配等问题主要的解决方法就是在一个母字符串当中找出每个目标子串在母串中的个数,找出出现次数最多的子串, 而且,这道题还略带一点贪心的思想;当然解决这一类字符串的题目有很多种方法,本次采用最传统的解决办法:


代码如下:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int a[310][310];
int main() {
    
    int t,i,max;
    
    while(scanf("%d%*c",&t)!=EOF&&t) {
        while(t--)  {
            char ans1,ans2;
            max=-1;
            memset(a,0,sizeof(a));  //初始化数组;
            char str[210];
            gets(str);
            int len=strlen(str);
            for(i=0;i<len-1;i++) {
                
                    int x=(int)str[i];   //统计每个字符出现的个数;
                    int y=(int)str[i+1];
                    a[x][y]++;
                    if(a[x][y]>max) {   //循环替代掉子串数目较少的字符串;
                        max=a[x][y];
                        ans1=str[i];
                        ans2=str[i+1];
                        
                    } else if(a[x][y] == max && ( str[i] < ans1 || str[i]==ans1 && str[i+1] < ans2)) {  //更新;
                        ans1=str[i];
                        ans2=str[i+1];
                    }
            }       
            printf("%c%c\n",ans1,ans2);
        }
        printf("\n");
    }
     return 0;
}


当然,此类题目还可以有很多中解法,例如map容器,set等都可以轻松解决;后续解法待续。。。。