简单的模式匹配算法
int strStr(char * haystack, char * needle){
int i=0,j=0;
while(i<strlen(haystack)&&j<strlen(needle)){
if(haystack[i]==needle[j]){
i++;
j++;
}
else{
i=i-j+1;
j=0;
}
}
if(j==strlen(needle)) return i-j;
else return -1;
}
KMP算法 next数组,就是求字符串的每个位置的最长公共前后缀,就是当匹配到i不匹配时,将字符串往后移,在i之前重合了多少位,在将重合后的以为j与i进行匹配,实现i不回溯,b站av16828557讲的太好了
#include<stdio.h>
#include<string.h>//kmp
#include<stdlib.h>
void next_i(char a[],int n,int next[]){
int i=1,j=0;
next[0]=0;
while(i<n){
if(a[i]==a[j]){
j++;
next[i]=j;
i++;
}
else{
if(j>0) j=next[j-1];
else {
next[i]=j;
i++;
}
}
}
}
void move_next(int next[],int n){
int i;
for(i=n-1;i>0;i--)
next[i]=next[i-1];
next[0]=-1;
}
int strStr(char * haystack, char * needle){
int i=0,j=0,m=strlen(haystack),n=strlen(needle);
int *next;
next=(int*)malloc(sizeof(int)*n);
next_i(needle,n,next);
move_next(next,n);
while(i<m&&j<n){
if(haystack[i]==needle[j]){
i++;
j++;
}
else{
j=next[j];//如果不相等,j移到它所对应的最大后缀
if(j==-1){
i++;
j++;
}
}
}
if(j==n) return i-j;
else return -1;
}
int main(){
char a[30],b[30];
gets(a);
gets(b);
printf("%d ",strStr(a,b));
}
不知道为什么在leetcode 上过不去