XDU 1140 寻找万神(字符串匹配)

学会strstr的使用

strstr(str1,str2)函数用于判断字符串str2是否是str1的子串。如果是,则该函数返回str2在str1中首次出现的地址;否则,返回NULL。

#include<cstdio>
#include<cstring>
using namespace std;
int main()
{
    int n;
    while(~scanf("%d",&n)){
        int ans=0;
        char a[50000],b[50000];
        while(n--){
            scanf("%s",a);
            strcat(b,a);
            char *p=b,*o;
            while(o=strstr(p,"wanshen")){
                p=o+7;
                ans++;
            }
            strcpy(b,p);
        }
        printf("%d\n",ans);
    }
    return 0;
}

 

#include<bits/stdc++.h>
int n,cnt;
int next[50000];

void get_next(char S[])
{
    int Slen=strlen(S);
    int i=1,j=0;
    next[1]=0;
    while(i<Slen){
        if(j==0||S[i-1]==S[j-1]){
            i++;
            j++;
            next[i]=j;
        }
        else
            j=next[j];
    }
}
bool KMP(char S[],char T[])
{
    int i=0,j=1,Slen=strlen(S),Tlen=strlen(T);
    while(i<=Slen&&j<=Tlen){
        if(j==0||S[i-1]==T[j-1]){
            i++;
            j++;
        } 
        else
            j=next[j];
    }
    if(j>Tlen)
        return true;    
    return false;
}

int main()
{
    char s[50000],S[50000];
    char T[8]={"wanshen"};
    while(scanf("%d",&n)!=EOF){
        cnt=0;
        while(n--){
            scanf("%s",s);
            strcat(S,s);
            get_next(S);
            char *o,*p=S;
            while(o=strstr(p,"wanshen")){
                if(KMP(S,T)) cnt++; 
                p=o+7;
            }
            strcpy(S,p);
        }
        printf("%d\n",cnt);
    } 
}
posted @ 2017-02-26 22:14  despair_ghost  阅读(156)  评论(0编辑  收藏  举报