1 一般方法
#inlucde <iostream>
using namespace std;
int match(char* P,char* T){
int n = strlen(T),i = 0; //文本串
int m = strlen(P),j = 0; //模式串
if(n < m)
return -1; //如果文本串比模式串还短,直接返回
for(i = 0;i < n-m+1; i++){
for(j = 0;j < m; j++){
if(T[i+j] != P[j])
break;
}
if(j >= m)
break;
}
if(i > n-m)
return -1;
return i;
}
void test(){
char* a = "0123456789";
char* b = "789";
cout << match(b, a) << endl;
}
int main(){
test();
return 0;
}
2 KMP算法
#include <iostream>
#include <string>
using namespace std;
int* getnext(char* p) { //模式串的next表 相当于模式串自匹配的过程
int m = strlen(p), j = 0; //"主"串指针
int* N = new int[m];
int t = N[0] = -1; //模式串指针
while (j < m - 1) {
if (t < 0 || p[j] == p[t]) {
j++;
t++;
N[j] = t;
}
else {
t = N[t];
}
return N;
}
}
int match(char* P, char* T) {
//P是模式串,短串 T是文本串,长串
int* next = getnext(P);
int n = (int)strlen(T), i = 0; //文本串指针
int m = (int)strlen(P), j = 0; //模式串指针
while (j < m && i < n) {
if (j < 0 || T[i] == P[j]) {
i++;
j++;
}
else {
j = next[j];
}
}
delete[] next;
return i - j;
}
void test() {
char a[] = "0123456789";
char b[] = "789";
cout << match(b, a) << endl;
}
int main() {
test();
return 0;
}