KMP算法-C++实现

KMP算法的C++实现,Macos下Xcode编译通过

代码如下:

#include<vector>
#include<iostream>
#include<stdlib.h>

using namespace std;

void cal_next_array(int pattern_length , char * pattern_str , int next[]){
    int k = -1;
    next[0] = k;
    for (int i = 1; i < pattern_length;  i ++) {
        while ( k > -1 && pattern_str[k+1] != pattern_str[i]) {
            k = next[k];
        }
        if( pattern_str[k+1] == pattern_str[i] ){
            k ++;
        }
        next[i] = k;
    }
}

int kmp( char * source , char * pattern , int sourceLength , int  patternLength ){
    if( patternLength <= 0 || sourceLength <= 0 || sourceLength < patternLength || source == NULL || pattern == NULL  ){
        return -1;
    }
    int * next = (int *)malloc( sizeof(int) * patternLength );
    cal_next_array(patternLength,pattern,next);
    int k = -1;
    for ( int  i = 0 ; i < sourceLength;  i ++) {
        while ( k > -1 &&  pattern[k+1] != source[i] ) {
            k = next[k];
        }
        if( pattern[k+1] == source[i]){
            k ++;
        }
        if( k == patternLength - 1){
            delete next;
            return i - patternLength + 1;
        }
    }
    delete next;
    return -1;
}

int main(){
    char source[] = "abcaabcab";
    char pattern[] = "abcab";
    cout << kmp(source, pattern, sizeof(source) -1 , sizeof(pattern) -1 )<<endl;
    return 1;
}
标签: none
返回文章列表 文章二维码
本页链接的二维码
打赏二维码