KMP算法

KMP算法

KMP算法的next数组

[LeetCode]KMP——字符串匹配

leetcode28

class Solution {
public:
    /*//暴力法
    int strStr(string haystack, string needle) {
        int i = 0,j = 0;
        if(needle.empty())
            return 0;
        while(i<haystack.size()&&j<needle.size())
        {
            if(haystack[i] == needle[j])
            {
                i++;
                j++;
            }
            else
            {
                i = i-j+1;
                j = 0;
            }
            if(j == (needle.size()))
                return i-j;
        }
        return -1;
        
    }
    */
    vector<int> cal_next(string p)
{
	vector<int> next(p.size(),0);

	next[0] = -1;
	int j = 0, k = -1;
	while (j < p.size() - 1) {

		if (k == -1 || p[j] == p[k]) {
            
            if(p[j+1] == p[k+1])
                next[++j] == next[++k];
            else
			next[++j] = ++k;

		}
		else {

			k = next[k];

		}

	}

	return next;
}

int strStr(string haystack, string needle) {
	if (needle.empty())return 0;
	vector<int> next = cal_next(needle);
	int i = 0, j = 0;
	while(i<haystack.size() && j<(int)needle.size())//一个大坑,不加(int)的话,size()为无符号类型,当j==-1时将会被转化为INT_MAX!
	{
		if (j == -1 || haystack[i] == needle[j])// 当j为-1时,要移动的是i,当然j也要归0
		{
			i++;
			j++;
		}
		else
		{
			j = next[j];
		}
	}
	if (j == needle.size())
		return i - j;
	else
		return -1;


}
};

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值