字符串匹配:暴力和KMP

1.牛客———兔子的名字 链接标题
题目简介:有n个字符串T和m个字符串S,对于每一个T统计有多少个字符串S是其子序列。
思路:对于每一个T暴力匹配统计有多少个字符串S是其子序列。

#include<bits/stdc++.h>
using namespace std;
char t[1005][105],s[105][50];
int main()
{
    int n,m;
    scanf("%d%d",&n,&m);
    for(int i=0;i<n;i++)
    scanf("%s",t[i]);
    for(int i=0;i<m;i++)
    scanf("%s",s[i]);
    for(int i=0;i<n;i++)
    {
        int ans=0;
        for(int j=0;j<m;j++)
        {
            int len1=strlen(t[i]),len2=strlen(s[j]),k=0,l=0;
            while(k<len1&&l<len2)
            {
                if(t[i][k]==s[j][l])
                {
                    k++;
                    l++;
                }
                else k++;
            }
            if(l>=len2) ans++;
        }
        printf("%d\n",ans);
    }
 } 
#include<bits/stdc++.h>
using namespace std;
const int N=1e6+7;
int Nextval[N],n,m;
char s[N],t[N];
void getNext()
{
    int j=0,k=-1;
    Nextval[0]=-1;
    while(j<m-1)
    {
        if(k==-1||t[k]==t[j])
        {
            k++;
            j++;
            if(t[k]!=t[j])
            Nextval[j]=k;
            else Nextval[j]=Nextval[k];
        }
        else k=Nextval[k];
    }
 }
 int kmp()
 {
     int i=0,j=0,ans=0;
     getNext();
     while(i<n&&j<m)
     {
         if(j==-1||s[i]==t[j])
         {
             if(j+1==m)
             {
                 j=Nextval[j];
                 ans++;
            }
            else i++,j++; 
         }
         else j=Nextval[j];
     }
    return ans;
  } 
int main()
{
    scanf("%s%s",s,t);
    n=strlen(s),m=strlen(t);
    int res=kmp();
    if(res) printf("YES\n%d\n",res);
    else printf("NO\n"); 
} 
全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务