代码随想录:KMP算法、BF算法
解决字符串匹配的问题
文本串:aabaabaaf
模式串:aabaaf
BF算法:
暴力匹配:时间复杂度O(m*n)
int Index_BF(string s, string t){
int i = 0;
int j = 0;
while(i < s.size() && j < t.size())
{
if(s[i] == t[j])
{
i++;
j++;
}
else
{
i = i - j + 1;
j = 0;
}
}
if(j >= t.size())
return i - t.size(); //匹配成功返回文本串下标
else
return -1; //没有匹配成功
}
KMP算法:
时间复杂度:O(m+n)
前缀:包含首字符不包含尾字母的所有子串
后缀:包含尾字符不包含首字母的所有子串
前缀表:寻找最长相等前后缀的长度 ——> next数组
a 0 aa 1 aab 0 aaba 1 aabaa 2 aabaaf 0
#include <iostream>
#include <string>
using namespace std;
int Index_KMP(string s, string t) {
int next[t.size()];
get_next(next, t);
int j = 0;
for(int i=0; i < s.size(); i++)
{
while(j > 0 && s[i] != t[j])
j = next[j-1];
if(s[i] == t[j])
j++;
if(j == t.size())
return i - t.size() + 1;
}
return -1;
}
//得到next数组
void get_next(int *next, string &str) {
//初始化
int i; //指向后缀末尾位置
int j = 0; //指向前缀末尾位置,也表示i之前子串的最长相等前后缀的长度
next[0] = 0;
for(i = 1; i < str.size(); i++)
{
while(j > 0 && str[i] != str[j]) //处理前后缀不同的情况
{
j = next[j - 1];
}
if(str[i] == str[j]) //处理前后缀相同的情况
j++;
next[i] = j; //得到next数组的值
}
}