字符串匹配问题——KMP算法实现

本文介绍了一种经典的字符串搜索算法——KMP算法,并通过Java代码详细展示了如何实现该算法来查找一个字符串在另一个字符串中的位置。首先通过计算next数组预处理模式串,然后进行匹配过程,最终返回匹配的位置。

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

public class Main {
	public int[] findNext(String str) {
		int[] next = new int[str.length()];
		char[] c = str.toCharArray();
		next[0] = 0;
		if(str.length() == 1) 
			return next;
		else {
			for(int i=1; i< c.length; i++) {
				int tmp = next[i-1];
				if(c[tmp] == c[i])
					next[i] = next[i-1] + 1;
				else {
					if(c[0] == c[i])
						next[i] = 1;
					else
						next[i] = 0;
				}
			}
			return next;
		}
	}
	
	public int KMP(String A,String B) {
		if(A.length() < B.length())
			return -1;
		int[] next = findNext(B);
		int s1 = 0;
		int s2 = 0;
		char[] a = A.toCharArray();
		char[] b = B.toCharArray();
		while(s1 < A.length()) {
			while(s2 < B.length() && a[s1] == b[s2]){
				s1++;
				s2++;
			}
			if(s2 == B.length())
				return s1-B.length();
			
			if(s2 == 0) {
				s1++;
				s2++;
			}
			else {
				int key = next[s2-1];			
				s1 = s1 - key;
				s2 = key;
			}
		}
		return 0;
	}
	
	public static void main(String[] args) {
		Main m = new Main();
		String A = "aaccaaccaa";
		String B = "aaccaa";
		int s = m.KMP(A, B);
		System.out.println(B);
		System.out.println("================");
		int l = A.length();
		char[] a = A.toCharArray();
		System.out.print(s+":");
		for(int i=s; i < s+B.length(); i++) 
			System.out.print(a[i]);
	}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值