3.2 Implement strStr()

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

我的初始思路:先在haystack里找到needle的第一个字符,若找到,继续比较haystack的余下字符和needle的余下字符。若有字符不相等,则返回null。代码如下:

public class Solution {
    public String strStr(String haystack, String needle) {
        if(needle == "") return haystack;
        int i = 0;
        int j = 0;
        char first = needle.charAt(j);
        while(i < haystack.length()){
            if(haystack.charAt(i) != first){
                i++;
            }
            else break;
        }
        if(i == haystack.length()) return null;
        while(i < haystack.length() && j < needle.length()){
            if(haystack.charAt(i) != needle.charAt(j)) return null;
            else{
                i++;
                j++;
            }
        }
        if(i == haystack.length() && j < needle.length()) return null;
        return needle;
    }
}

这个思路是错误的。因为即使haystack和needle的余下字符不等,在haystack里找到一个新的位置,使它等于needle.charAt(0),还是有可能找到相等的。比如haystack = "abcaecd", needle = "cd".。按我这个思路,当找到c = c, 我们发现a (in haystack) != d in needle,于是返回null.

Approach I: Brute-fore

”假设原串的长度是n,匹配串的长度是m。思路很简单,就是对原串的每一个长度为m的字串都判断是否跟匹配串一致。“

Ref: http://blog.csdn.net/linhuanmars/article/details/20276833

public class Solution {
    public String strStr(String haystack, String needle) {
        //to compare each block (size = needle size) of haystack with needle
        if(haystack == null || needle == null || needle.length() == 0){ 
            return haystack;
        }
        if(needle.length() > haystack.length()){
            return null;
        }
        for(int i = 0; i <= haystack.length() - needle.length(); i++){
            boolean flag = true;
            for(int j = 0; j < n; j++){
                if(haystack.charAt(i + j) != needle.charAt(j)){
                    flag = false;
                    break;
                }
            }
            if(flag == true) return haystack.substring(i);
        }
        return null;
    }
}


Approach II: http://blog.csdn.net/linhuanmars/article/details/20276833

Note: My submission @https://oj.leetcode.com/submissions/detail/20217240/ has errors:

  • my for loop (below) looks different from linhua's, but essentially they are the same. 

       for(int j = 0; j < haystack.length() - needle.length(); j++){
            hayHash = (hayHash - tmpBase*haystack.charAt(j)) * base + haystack.charAt(j+needle.length());
             if(hayHash == needleHash){
                 return j+1;
             }
        }

  • The only thing that causes error is: set hashcode type to "long" not "int".


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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值