zoukankan      html  css  js  c++  java
  • kmp算法模板

    t是模式串,s是需要被匹配的串。

    #include<iostream>
    #include<cstdio>
    #include<cstring>
    using namespace std;
    const int maxn = 100000;
    int nextval[maxn];
    void get_next(char* T)
    {
        int i = 1, j = 0;
        nextval[1] = 0;
        int len = strlen(T+1);
        while(i < len)
        {
            if(j == 0 || T[i] == T[j])
            {
                ++i;
                ++j;
                if(T[i] == T[j])
                    nextval[i] = nextval[j];
                else 
                    nextval[i] = j;
            }
            else 
                j = nextval[j];
        }
    }
    int kmp(char* T, char* S)
    {
        int lent = strlen(T+1), lens = strlen(S+1);
        int i = 1, j = 1;
        while(i <= lens && j <= lent)
        {
            if(j == 0 || S[i] == T[j])
            {
                ++i;
                ++j;
            }
            else 
                j = nextval[j];
        }
        if(j > lent)
            return i - lent;
        return 0;
    }
    int main()
    {
        freopen("input.txt", "r", stdin);
        freopen("output.txt", "w", stdout);
        char t[maxn], s[maxn];
        scanf("%s", t + 1);
        scanf("%s", s + 1);
        memset(nextval, 0, sizeof(nextval));
        get_next(t);
        int pos = kmp(t, s);
        printf("pos = %d
    ", pos);
    }
    
  • 相关阅读:
    正则表达式复习 (?<=) (?=)
    HTML 30分钟入门教程
    C# 多线程详解
    C# List
    C# 枚举
    C# 线程数
    C# 泛型2
    C# 泛型
    C# 结构体
    不用Google Adsense的84个赚钱方法
  • 原文地址:https://www.cnblogs.com/KeepZ/p/11636791.html
Copyright © 2011-2022 走看看