1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
| #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; }
|