大学狗,期末复习数据结构到模式匹配这一块,顺便就把书上的几个算法详细地写了一遍。
下面这个程序中包含三个字符串匹配的方法,分别是:常规的从左往右匹配法,先首尾后中间匹配法,以及经典的KMP算法。
前两种算法适用于下标从0开始的字符串,KMP算法适用于下标从1开始的字符串。KMP算法处理下标从0开始的字符串,next函数使用的时候会出现问题,
所以只能从下标1开始(所以我测试的字符串的首位是用1占位),如果有大神知到怎样改到可以从零开始,求赐教!!!
编译环境为vs2013
// ConsoleApplication5.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include "string.h"
#include "stdlib.h"
//按顺序依次对比,适用于字符串下标从0开始
int IndexOrd(char* S,char* T,int pos)
{
int s = strlen(S);;
int t = strlen(T);
for (int i = pos;i<s-t;i++)
{
int temp = i;
for (int j = 0; j <t; j++)
{
if (S[temp] == T[j])
{
printf("%c ",S[temp]);
temp++;
}
else
{
break;
}
}
if (temp - i == t)
return i;
}
return 0;
}
//先比较首尾,后比较中间,适用于字符串下标从0开始
int Index_Fl(char* S,char* T,int pos)
{
int s = strlen(S);
int t = strlen(T);
int start, end;
for (int i = pos; i < s - t;)
{
start = i;
end = start + t - 1;
if (S[start] != T[0])
{
i++;
}
else if (S[end]!=T[t-1])
{
i++;
}
else
{
int temp = i+1;
int k = 1;
while (temp<i+t-1)
{
if (S[temp] = T[k])
{
temp++;
k++;
}
else
break;
}
if (temp - i == t)
{
return i;
}
else
i++;
}
}
return 0;
}
//KMP算法,适用于字符串下标从1开始
//判断是否相等
bool isEqual(char*S, int pos, int num)
{
for (int i = 1; i <=num; i++)
{
if (S[i] != S[pos - num + i-1])
return false;
}
return true;
}
int* getArray(char* S)
{
int* next;
int s = strlen(S);
next = (int*)malloc((s)*sizeof(int));
next[0] = s;
for (int j = 1; j < s; j++)
{
if (j == 1)
{
next[j] = 0;
}
else
{
int k = 1;
int max = 1;
while (k+1<j)
{
if (isEqual(S, j, k))
{
max = k + 1;
}
k++;
}
next[j] = max;
}
}
return next;
}
int KMPsearch(char* S,char* T,int pos,int* next)
{
int i = pos;
int j = 1;
int s = strlen(S);
int t = strlen(T);
int w = 0;
for (;j<t&&i<s;)
{
if (S[i] == T[j])
{
i++; j++;
}
else
{
printf("\nj=%d,next[%d]=%d",j,j,next[j]);
j = next[j];
if (j == 0)
{
i++;
j = 1;
}
}
}
if (j == t)
return i+1-t;
else
return -1;
}
int _tmain(int argc, _TCHAR* argv[])
{
char a[] = "abcdef";
char b[] = "e";
int m = Index_Fl(a,b,0);
printf("结果是:%d\n",m);
int* s;
char S[] = "1acabaabaabcacaabc";
s = getArray("1abaabcac");
for (int i = 0; i < 9; i++)
{
printf("%d ",s[i]);
}
int n = KMPsearch(S, "1abaabcac",1,s);
printf("结果是:%d\n", n);
}