字符串匹配(蛮力、KMP)
串S
s.substr(k) 从第k个字符到结尾
s.substr(k,n) 从第k个字符到k后n个字符
串匹配
功能要求
评价标准
文本串长度n
模式串长度m
蛮力匹配
时间复杂度
O(n x m) —>O(n) (随着字母表自身越大,效率越高)
(蛮力算法)有助于理解过程、找出改进的起点
字母表自身大小:越小,最坏情况出现的概率越高。
模式串长度:越大,最坏情况的后果越严重。
KMP算法
时间复杂度
O(m+n)
主要思想
1.最大程度上增加移动位数
2.避免大量重复的比对
主程序以及构造next查询表
#include<iostream>
using namespace std;
int match(char* p, char* t);
int* buildnext(char* p);
int main()
{
char* title = "edgupup";
char* name = "upup";
cout << "目标字符串首字母地址 : " << match(name,title) << endl;
system("pause");
return 0;
}
int match(char* p, char* t)
{
int* next = buildnext(p);
int n = strlen(t), i = 0;
int m = strlen(p), j = 0;
while (i < n&&j < m)
{
if (0 > j || t[i] == p[j])
{
i++;
j++;
}
else
{
j = next[j];
}
}
return i - j;
}
int* buildnext(char* p)
{
int m = strlen(p), j = 0;
int* N = new int(m);
int t = N[0] = -1;
while (j < m - 1)
{
if (0 > t || p[j] == p[t])
{
t++; j++;
N[j] = p[j] != p[t] ? t : N[t];
}
else
{
t = N[t];
}
}
return N;
}