朴素模式匹配算法
# include <stdlib.h>
# include <iostream>
# include <stdio.h>
# define MaxSize 255
typedef struct {
char ch[ MaxSize] ;
int length;
} SString;
SString InitStr ( SString & S) {
S. length= 0 ;
return S;
}
SString SetStr ( SString & S) {
char c;
int i= 1 ;
scanf ( "%c" , & c) ;
while ( c!= '\n' ) {
S. ch[ i++ ] = c;
S. length++ ;
scanf ( "%c" , & c) ;
}
return S;
}
int Index ( SString & S, SString & D) {
int i= 1 , j= 1 ;
while ( i<= S. length&& j<= D. length) {
if ( S. ch[ i] == D. ch[ j] ) {
++ i;
++ j;
}
else {
i= i- j+ 2 ;
j= 1 ;
}
}
if ( j> D. length) {
return i- D. length;
}
else return 0 ;
}
int main ( ) {
SString S;
SString D;
InitStr ( S) ;
InitStr ( D) ;
printf ( "输入主串:" ) ;
SetStr ( S) ;
printf ( "输入子串:" ) ;
SetStr ( D) ;
printf ( "-------朴素模式匹配:--------\n" ) ;
int i;
i = Index ( S, D) ;
if ( i> 0 ) printf ( "匹配成功,位置是:%d" , i) ;
else printf ( "匹配失败" ) ;
return 0 ;
}
KMP算法
# include <stdlib.h>
# include <iostream>
# include <stdio.h>
# define MaxSize 255
typedef struct {
char ch[ MaxSize] ;
int length;
} SString;
SString InitStr ( SString & S) {
S. length= 0 ;
return S;
}
SString SetStr ( SString & S) {
char c;
int i= 1 ;
scanf ( "%c" , & c) ;
while ( c!= '\n' ) {
S. ch[ i++ ] = c;
S. length++ ;
scanf ( "%c" , & c) ;
}
return S;
}
void Get_Next ( SString & D, int * next) {
int i= 1 , j= 0 ;
next[ 1 ] = 0 ;
while ( i< D. length) {
if ( j== 0 || D. ch[ i] == D. ch[ j] ) {
++ i; ++ j;
next[ i] = j;
}
else {
j= next[ j] ;
}
}
}
void Get_NextVal ( SString D, int * next, int * nextval) {
nextval[ 1 ] = 0 ;
for ( int j= 2 ; j< D. length; j++ ) {
if ( D. ch[ next[ j] ] == D. ch[ j] )
nextval[ j] = nextval[ next[ j] ] ;
else
nextval[ j] = next[ j] ;
}
}
int Index_KMP ( SString & S, SString & D, int * next) {
int i= 1 , j= 1 ;
while ( i<= S. length&& j<= D. length) {
if ( j== 0 || S. ch[ i] == D. ch[ j] ) {
++ i; ++ j;
}
else
j= next[ j] ;
}
if ( j> D. length)
return i- D. length;
else
return 0 ;
}
void PrintNext ( SString D, int * next) {
for ( int i= 1 ; i< D. length+ 1 ; i++ ) {
printf ( "%d " , next[ i] ) ;
}
printf ( "\n" ) ;
}
int main ( ) {
SString S;
SString D;
InitStr ( S) ;
InitStr ( D) ;
printf ( "输入主串:" ) ;
SetStr ( S) ;
printf ( "输入子串:" ) ;
SetStr ( D) ;
printf ( "----------------KMP----------------\n" ) ;
int next[ D. length+ 1 ] ;
Get_Next ( D, next) ;
printf ( "输出next数组:" ) ;
PrintNext ( D, next) ;
printf ( "输出优化后next数组:" ) ;
int nextval[ D. length+ 1 ] ;
Get_NextVal ( D, next, nextval) ;
PrintNext ( D, nextval) ;
int loc;
loc= Index_KMP ( S, D, next) ;
if ( loc> 0 ) printf ( "匹配成功,位置是:%d" , loc) ;
else printf ( "匹配失败" ) ;
return 0 ;
}