#include <iostream>
using namespace std;# define MAXSIZE 10
//暴力匹配
int VoilentMath( const char* s, const char* p){
int slen = strlen(s);
int plen = strlen(p);
int i =0;
int j =0;while(i < slen && j < plen){if(s[i]== p[j]){
i++;
j++;}else{
i = i - j + 1;
j =0;}}if(j == plen){return i - j;}else{return -1;}}
KMP算法
求数组next:
#include<iostream>]#include<string>
using namespace std;#define MAXSIZE 50
void getNext(int next[], string t){
int j =0, k = -1;
next[0]= -1;while(j<t.length() - 1){if(k == -1 || t[j]== t[k]){
++j;
++k;
next[j]= k;}else{
k = next[k];}}}
匹配
int KmpSearch(string s, string p){
int j =0;
int i =0;
int slen = s.length();
int plen = p.length();
int next[MAXSIZE];
getNext(next, p);while(i < slen && j < plen){if(j == -1 || s[i]== p[j]){
i++;
j++;}else{
j = next[j];}}if(j == plen)return i - j;elsereturn -1;}
int main(){
int m =KmpSearch("abcdffgf", "ffg");
cout << m << endl;}