# 传统的字符串匹配

## ２．代码实现：

#include<stdio.h>
#include<string.h>
#include<iostream>
#include<algorithm>
using namespace std;

int main()
{
char name1[100] = {"abababdcd"};
char name2[100] = {"ababd"};
int len1 = strlen(name1);
int len2 = strlen(name2);
int ding1 = 0;
int ding2 = 0;
while(ding1 < len1 && ding2 < len2){
if(name1[ding1] == name2[ding2]){
++ding1;
++ding2;
}else{
ding1 = ding1-ding2+1;
ding2 = 0;
}
}
if(ding2 == len2){
printf("YES\n");
}else printf("NO\n");
return 0;
}


# 模式匹配的改进算法——KMP

## １．思路：

 主串 子串 a b a b a b d c b a b a b d

 主串 子串 a b a b a b d c b a

 主串 子串 a b a b a b d c b a b

## ２．代码实现：

#include<stdio.h>
#include<string.h>
#include<iostream>
#include<algorithm>
using namespace std;

char name1[10] = {"abababdcd"};
char name2[10] = {"ababd"};
int len1 = strlen(name1);
int len2 = strlen(name2);
int ding1 = 0;
int ding2 = 0;

int next[10];//我们用next数组来存储不匹配时，当前字符应该对应的子串的位置。

void GetNext()
{
int i = 0;
int k = -1;
next[0] = -1;
while(i < len2){
if((k == -1) || (name2[i]==name2[k]))
next[++i] = ++k;
else
k = next[k];
}
}

int main()
{
GetNext();

while(ding2 < len2){
while(ding2 != -1 && name1[ding1] != name2[ding2]){
ding2 = next[ding2];
}
ding1++;
ding2++;
}

if(ding2 == len2){
printf("YES\n");
}else printf("NO\n");
return 0;
}


03-30 318
04-13 441
10-06 10万+
05-18 4404
01-03 3198
05-13 2936
11-24 374
01-22 340
08-18 71
08-27 3488
04-12 249
04-13 186
02-24 874
03-21 68