zoukankan      html  css  js  c++  java
  • Luogu3375 【模板】KMP字符串匹配

    复习字符串ing
    KMP模板

    #include <iostream>
    #include <cstdio>
    #include <cstring>
    #include <algorithm>
    #include <cmath>
    #define R(a,b,c) for(register int  a = (b); a <= (c); ++ a)
    #define nR(a,b,c) for(register int  a = (b); a >= (c); -- a)
    #define Max(a,b) ((a) > (b) ? (a) : (b))
    #define Min(a,b) ((a) < (b) ? (a) : (b))
    #define Fill(a,b) memset(a, b, sizeof(a))
    #define Abs(a) ((a) < 0 ? -(a) : (a))
    #define Swap(a,b) a^=b^=a^=b
    #define ll long long
    
    #define ON_DEBUG
    
    #ifdef ON_DEBUG
    
    #define D_e_Line printf("
    
    ----------
    
    ")
    #define D_e(x)  cout << #x << " = " << x << endl
    #define Pause() system("pause")
    #define FileOpen() freopen("in.txt","r",stdin);
    
    #else
    
    #define D_e_Line ;
    #define D_e(x)  ;
    #define Pause() ;
    #define FileOpen() ;
    
    #endif
    
    struct ios{
        template<typename ATP>ios& operator >> (ATP &x){
            x = 0; int f = 1; char c;
            for(c = getchar(); c < '0' || c > '9'; c = getchar()) if(c == '-')  f = -1;
            while(c >= '0' && c <= '9') x = x * 10 + (c ^ '0'), c = getchar();
            x*= f;
            return *this;
        }
    }io;
    using namespace std;
    
    const int N = 1000007;
    
    int n, len1, len2;
    int nxt[N];
    char str1[N], str2[N];
    
    inline void GetNext(){
    	int i = 0, j = -1;
    	nxt[0] = -1;
    	while(i < len2){
    		if(j == -1 || str2[i] == str2[j])
    			nxt[++i] = ++j;
    		else
    			j = nxt[j];
    	}
    }
    inline void KMP(){
    	int i = 0, j = 0;
    	while(i < len1){
    		if(j == -1 || str1[i] == str2[j])
    			++i, ++j;
    		else
    			j = nxt[j];
    		if(j == len2){
    			printf("%d
    ", i - len2 + 1);
    			j = nxt[j];
    		}
    	}
    }
    
    int main(){ 
    //FileOpen();
    
        scanf("%s%s", str1, str2);
        len1 = strlen(str1), len2=strlen(str2);
        
        GetNext();
        KMP();
        
        R(i,1,len2){
        	printf("%d ", nxt[i]);
        }
        return 0;
    }
    

  • 相关阅读:
    利用哈希map快速判断两个数组的交集
    TCP协议中的三次握手和四次挥手(图解)-转
    PC,移动端H5实现实现小球加入购物车效果
    HQL和SQL的区别
    Java泛型详解,通俗易懂只需5分钟
    经典的 Fork 炸弹解析
    Java并发之AQS详解
    Java不可重入锁和可重入锁的简单理解
    Codeforces 1215F. Radio Stations
    Codeforces 1215E. Marbles
  • 原文地址:https://www.cnblogs.com/bingoyes/p/11237292.html
Copyright © 2011-2022 走看看