字符串KMP算法-java

本文深入探讨了KMP算法的思想及其在字符串匹配中的应用,并提供了详细的代码实现。通过对比传统方法,阐述了KMP算法如何高效地进行模式匹配,避免了不必要的回溯,达到了O(m+n)的时间复杂度。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

KMP算法思想的学习,是参考的博客http://kb.cnblogs.com/page/176818/

真正具体实现的时候,会发现代码思想 与算法过程有些偏颇(当然这是很正常的),贴上代码供以后参考。

public class ImplementStrStr {
	public int strStr(String haystack, String needle) {
		if(needle.length() == 0) return 0;
		
        int[] next = next(needle);
        int i = 0, j = 0;
        
        while(i < haystack.length() && j < needle.length()) {
        	if(j == -1 || haystack.charAt(i) == needle.charAt(j)) {
        		++i;
        		++j;
        	}
        	else
        		j = next[j]; //不匹配时,需要将待匹配子串的指针j移动到相应位置(该位置由next()函数提供)
        }
        
        return j >= needle.length() ? i - needle.length() : -1;
    }
	// next函数,求子串指针j的移动位置
	public int[] next(String needle) {
		int len = needle.length();
		int[] next = new int[len];
		
		int i = 0, j = -1;
		next[0] = -1;
		
		while(i < len - 1) {
			if(j == -1 || needle.charAt(i) == needle.charAt(j)) {
				++i;
				++j;
				next[i] = (needle.charAt(i) == needle.charAt(j) ? next[j] : j);
			}
			else
				j = next[j];
		}
		
		return next;
	}
}

同时,这也是LeetCode题目Implement StrStr() 的解。

在我看完链接博客所述的算法思想后,以为代码中实现的也会是对指针i的移动,却没想是j的变化。

KMP算法复杂度为O(m+n).



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值