leetcode Implement strStr()

本文深入探讨了Java中字符串匹配问题的两种解决方案:使用内置的indexOf方法和实现经典的KMP算法。通过对比这两种方法的原理、代码实现及效率分析,旨在为读者提供全面的理解和实践指导。

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

https://oj.leetcode.com/problems/implement-strstr/

字符串匹配在java中inexof()能解决这个问题。

public class Solution {
    public int strStr(String haystack, String needle) {
        return haystack.indexOf(needle);
        
    }
}

当然写一个KMP算法才是真正的练习:

public class Solution {
    public int strStr(String haystack, String needle) {
    	int hlen=haystack.length();
		int nlen=needle.length();
		if(needle.equals("")){return 0;}
		if(haystack.equals("")){return -1;}
		int []next=getNext(needle);
		int i=0;
		int j=0;
		while(i<hlen&&j<nlen){
			if(j==-1||haystack.charAt(i)==needle.charAt(j)){
				i++;
				j++;
			}else{
				j=next[j];
			}
		}
		if(j==nlen){
			return i-j;
		}else 
			return -1;
		
	}
	public static int[] getNext(String str){
		int len=str.length();
		int[]ret=new int[len];
		ret[0]=-1;
		int k=-1;
		int j=0;
		while(j<len-1){
			if(k==-1||str.charAt(j)==str.charAt(k)){
				++k;
				++j;
				ret[j]=k;
			}else{
				k=ret[k];
			}
		}
		return ret;
	
}

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值