其他分享
首页 > 其他分享> > kmp tire字符串

kmp tire字符串

作者:互联网

kmp自身匹配和两者匹配,都是i和j+1匹配(让两个字符串从1开始)

自身匹配找ne【】数组的值,i从2开始,j从0开始

两者匹配,i从1开始,j从0开始

#include<iostream>
using namespace std ;
const int M = 1e5 + 10 , N = 1e6 + 10 ;
int a , b ;
char s[N] , p[M] ;
int ne[M] ;
int main()
{
    cin >> a >> p + 1 >> b >> s + 1 ;
    for(int i =  2 , j = 0 ; i <= a ; i++)
    {
        while(j&&p[i] != p[j+1]) j = ne[j] ;
        if(p[i] == p[j+1]) j++ ;
        ne[i] = j ;
    }
    for(int i =  1 , j = 0 ; i <= b ; i++)
    {
        while(j&&s[i] != p[j+1]) j = ne[j] ;
        if(s[i] == p[j+1]) j++ ;
        if(j == a)
        {
            printf("%d ", i - a);
            j = ne[j] ;
        }
    }
    return 0 ;
}

tire字符串看原来的博客

能用char , string不对

#include<iostream>
using namespace std ;
const int N = 1e5 +  10 ;
int son[N][26] ;
int cnt[N] , idx ;
char str[N] ;
void insert(char str[])
{
    int p = 0 ;
    for(int i = 0 ; str[i] ; i++)
    {
        int u = str[i] - 'a' ;
        if(!son[p][u]) son[p][u] = ++ idx ;
        p = son[p][u] ;
    }
    cnt[p] ++ ;
}
int query(char str[])
{
    int p = 0 ;
    for(int i = 0 ; str[i] ; i++)
    {
        int u = str[i] - 'a' ;
        if(!son[p][u]) return 0 ;
        p = son[p][u] ;
    }
    return cnt[p] ;
}
int main()
{
    int n ;
    cin >> n ;
    while(n--)
    {
      char op[2];
        scanf("%s%s",op,str);
        if (op[0] == 'I') insert(str);
        else printf("%d\n",query(str));
    }
    return 0 ;
}

标签:匹配,tire,int,son,char,++,str,kmp,字符串
来源: https://blog.csdn.net/weixin_51658930/article/details/122462138