• KMP算法


    对于KMP算法,最重要的是要把握其中的next数组的含义及求法

    考虑一个模式字符串:b1b2...bn,定义next[s]如下:

    next[s]  is the longest proper prefix of b1b2...bs that is also a suffix of b1b2...bs

    #include "kmp.h"
    #include <string.h>
    void makeNext(const char* patt, int* next){
    	int len = strlen(patt);
    	//next must be an array with len + 1 element
    	next[1] = 0;
    	int s = 0;
    	const char *p = patt - 1;
    	for (int t = 1; t < len; t++){
    		while (s > 0 && p[t + 1] != p[s + 1])
    			s = next[s];
    		if (p[t + 1] == p[s + 1]){
    			s += 1;
    			next[t + 1] = s;
    		}
    		else
    			next[t + 1] = 0;
    	}
    }
    int search(const char* src, const char* patt){
    	int pattLen = strlen(patt);
    	int srcLen = strlen(src);
    	int *next = new int[pattLen + 1];
    	memset(next, 0, (pattLen + 1) * sizeof(int));
    	makeNext(patt, next);
    	int i = 0;
    	int j = 0;
    	int result = -1;
    	for (i = 0; i < srcLen; i++){
    		while (j > 0 && src[i] != patt[j])
    			j = next[j];
    		if (src[i] == patt[j])
    			j++;
    		if (j == pattLen){
    			result = i - pattLen + 1;
    			break;
    		}
    	}
    	return result;
    }
    
  • 相关阅读:
    第六周学习报告
    第五周学习任务报告
    第四周学习任务报告
    第三周学习任务报告
    第二周(9.14-9.20)学习任务报告
    Top 参数解析
    unpipc.h
    linux 网络编程卷2 笔记
    mysql 主从及配置
    rsync linux
  • 原文地址:https://www.cnblogs.com/hustxujinkang/p/4483045.html
Copyright © 2020-2023  润新知