数据结构—模式匹配
原理:参考趣学数据结构
代码:
# include <stdio.h>
# include <stdlib.h>
# define N 100
int next[ N] ;
void getNext ( char * T, int * next, int m) { int j = 1 , k= 0 ; next[ j] = 0 ; while ( j <= m) { if ( k == 0 || T[ k] == T[ j] ) { next[ ++ j] = ++ k; } else { k = next[ k] ; } } for ( int i = 1 ; i <= m; i++ ) { printf ( "%d " , next[ i] ) ; }
}
int KMP ( char * S, char * T, int pos, int n, int m) { int i = pos, j = 1 ; while ( i <= n && j <= m) { if ( j== 0 || S[ i] == T[ j] ) { i++ ; j++ ; } else { j = next[ j] ; } } if ( j = m + 1 ) { printf ( "查找成功子串的初始位置为:%d\n" , i - j) ; return i - j; } printf ( "查找子串失败!\n" ) ; return - 1 ;
}
int main ( ) { char S[ 18 ] = "-adecadecadcbadcb" ; char T[ 10 ] = "-adecadcb" ; getNext ( T, next, 8 ) ; printf ( "\n" ) ; KMP ( S, T, 1 , 16 , 8 ) ; printf ( "\n" ) ; system ( "pause" ) ; return 0 ;
}
测试截图:
时间复杂度O(m+n),空间复杂度O(1)
如果存在什么问题,欢迎批评指正!谢谢!