KMP_java实现

本文详细介绍了一种高效的字符串匹配算法——KMP算法,并提供了完整的Java实现代码。通过该算法,可以快速定位目标子串在主串中的位置,适用于文本搜索等场景。

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

package test;




public class KMP {
	public int[] getNext(String p) {
		if(p == null || p.length() == 0)
			return null;
		int[] next = new int[p.length()];
		int i = 0;
		int j = -1;
		next[0] = -1;
		while(i < p.length() - 1) {
			if(j == -1 || p.charAt(i) == p.charAt(j)) {
				i++;
				j++;
				if(p.charAt(i) == p.charAt(j))
					next[i] = next[j];
				else
					next[i] = j;
			} else {
				j = next[j];
			}
		}
		return next;
	}
	
	public int KMP1(String s, String p) {
		if(s == null || p == null)
			return -1;
		int[] next = getNext(p);
		int res = -1;
		int i = 0;
		int j = 0;
		while(i < s.length()) {
			if(j == -1 || s.charAt(i) == p.charAt(j)) {
				i++;
				j++;
			} else {
				j = next[j];
			}
			if(j == p.length()) {
				res = i - p.length();
				break;
			}
			
		}
		return res;
	}
	public static void main(String[] arg) {
		KMP kmp = new KMP();
		System.out.println(kmp.KMP1("abcd", "abcdef"));
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值