[leetcode]Implement strStr()

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

 

Implement strStr().

Returns a pointer to the first occurrence of needle in haystack, or null if needle is not part of haystack.

 大海捞针,很贴切,好吧,我用暴力居然直接过了,羞愧....

JDK源码中有实现,就不罗嗦了,下午研究了一下KMP算法(O(M + N)),很不错的算法,明天好好整理一下,重新写一遍,并写一篇关于KMP算法的博文吧。

暴力——O(m*n)代码如下:

    public String strStr(String haystack, String needle) {
		if(needle == null || needle.length() == 0 || haystack == null){
			return haystack;
		}
		int hayStackLen = haystack.length();
		int needleLen = needle.length(); 
		if(hayStackLen < needleLen || (hayStackLen == needleLen && !haystack.equals(needle))){
			return null;
		}
		char first = needle.charAt(0);
		int max = hayStackLen - needleLen + 1;
		for(int i = 0; i < max; i++){
			if(haystack.charAt(i) != first){
				while(++i < max && haystack.charAt(i) != first);
			}
			if(i < max){
				int j = i + 1;
				int end = j + needleLen - 1;
				for(int k = 1; j < end && needle.charAt(k) == haystack.charAt(j); j++,k++);
				if(j == end){
					return haystack.substring(i);
				}
			}
		}
		return null;
	}

 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值