KMP 文本字符串匹配算法

1. 首先将pattern_str模式串预处理,生成next数组

2. 进入主循环,遍历query字符串的每一个字符

    2.1. 比较query和pattern_str的字符

    2.2. 当发现不匹配字符时,查询next数组,得到匹配前缀所对应的最长可匹配前缀子串,移动pattern_str到对应位置

    2.3.if 当前字符匹配,则继续循环

next数组是指pat到当前字符之前(去除当前字符)的字符串的最大公共前缀后缀长度。

class Solution {
public:
    void getNext(vector<int>& next, const string& s) {
        int j = -1;
        next[0] = j;
        for(int i = 1; i < s.size(); i++) { // 注意i从1开始
            while (j >= 0 && s[i] != s[j + 1]) { // 前后缀不相同了
                j = next[j]; // 向前回溯
            }
            if (s[i] == s[j + 1]) { // 找到相同的前后缀
                j++;
            }
            next[i] = j; // 将j(前缀的长度)赋给next[i]
        }
    }
    int strStr(string haystack, string needle) {
        if (needle.size() == 0) {
            return 0;
        }
        vector<int> next(needle.size());
        getNext(next, needle);
        int j = -1; // // 因为next数组里记录的起始位置为-1
        for (int i = 0; i < haystack.size(); i++) { // 注意i就从0开始
            while(j >= 0 && haystack[i] != needle[j + 1]) { // 不匹配
                j = next[j]; // j 寻找之前匹配的位置
            }
            if (haystack[i] == needle[j + 1]) { // 匹配,j和i同时向后移动
                j++; // i的增加在for循环里
            }
            if (j == (needle.size() - 1) ) { // 文本串s里出现了模式串t
                return (i - needle.size() + 1);
            }
        }
        return -1;
    }
}

// 实现二:
void get_next(const string& pattern_str, vector<int> & next)
{
	int j = 0;
	for (int i = 2; i < pattern_str.length(); i++)
	{
		while (j != 0 and (pattern_str[j] != pattern_str[i - 1]))
		{
			j = next[j];
		}
		if (pattern_str[j] == pattern_str[i - 1])
		{
			j++;
		}
		next[i] = j;
	}
}

int KMP(const string & query, const string & pattern_str)
{
	vector<int> next(pattern_str.length(), 0);
	get_next(pattern_str, next);
	int j = 0;
	for (int i = 0; i < query.length(); i++)
	{
		while (j > 0 and (pattern_str[j] != query[i]))
		{
			j = next[j];
		}
		if (pattern_str[j] == query[i])
		{
			j++;
		}
		if (j == pattern_str.length())
		{
			cout << "start_pos is " << i - pattern_str.length() + 1 << endl;
			return i - pattern_str.length() + 1;
		}
	}
	return -1;

}
int main() {
	cout << "hahaha" << endl;
	string query = "ATGTGAGCTGGTGTGTGCFAA";
	string pattern_str = "GTGTGCF";
	int a = KMP(query, pattern_str);
	cout << a << endl;

	return 0;
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

samoyan

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值