LeetCode_OJ【28】Implement strStr()

Implement strStr().

Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.

这题虽然用朴素字符串匹配算法也能过,但是最好还是用KMP算法,毕竟笔试面试的时候可没有这么简单。

KMP算法的精髓在于求出next数组,next数组记录的是模式串匹配失效后主串应该和模式串的哪一位进行比较:比如在模式串第j位匹配失效,那么下一步主串当前位应该和模式串第next[j]位相比较,如果再失效,则继续和模式串next[next[j]]位相比较。

KMP算法的时间复杂度为O(m+n),空间复杂度为O(m).

下面是java实现,需牢记。

public class Solution {
    public int strStr(String haystack, String needle) {
        if(needle == null || needle.length() == 0)
            return 0;
		int[] next = getNext(needle);
		for(int i = 0,j = -1; i < haystack.length() ; i ++){
			while(j > -1 && haystack.charAt(i) != needle.charAt(j +1)){
				j = next[j];
			}
			if(haystack.charAt(i) == needle.charAt(j +1)){
				j++;
				if( j == needle.length() -1)
					return i -j ;
			}
		}
        return -1;
    }
	
	public int[] getNext(String str){
		if(str ==null || str.length() == 0)
			return null;
		int[] next = new int[str.length() + 1];
		for(int i = 0 , j = -1 ; i < str.length() ; i ++){
			if(i == 0 ){
				next[i] = j;
				continue;
			}
			while(j > -1 && str.charAt(j) != str.charAt(i)){
				j = next[j];
			}
			if(str.charAt(i) == str.charAt(j + 1)) {
				j++;
			}
			next[i] = j;
		}
		return next;
	}
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值