implement strStr()

implement strStr()这就是第一次online coding遇到的题,竟然是leetcode原题,还是easy,偏偏一直没写过==,真该掌嘴。

思路简单,从0开始扫0+needle.length()的haystack的substring,match就return index,找不到就返回-1。 需要注意两个String “” 和 “” 要返回0。

这道题的时间复杂度比较坑,我再leetcode的discuss里面和别人讨论了很久,具体的连接在这里。我这样写会让时间复杂度变成O(N*M*M)。

public int strStr(String haystack, String needle) {
        if(haystack == null || needle == null || needle.length() > haystack.length()) return -1;
        if(haystack.length() == 0 && needle.length() == 0) return 0;
        int needleLen = needle.length();
        int haystackLen = haystack.length();
        int i = 0;
        while(i < haystackLen) {
            if(i + needleLen > haystackLen) return -1; // check if outOfBoundry
            if(haystack.substring(i, i + needleLen).equals(needle)) return i;
            i++;
        }
        return -1;
    }


这是不用substring写的,复杂度O(M*N)

public int strStr(String haystack, String needle) {
        if(haystack == null || needle == null) return -1;
        int hayLen = haystack.length();
        int needLen = needle.length();
        if(needLen > hayLen) return -1;
        if(needle.equals("")) return 0;
        
        int cnt = 0;
        int i = 0;
        
        while((i + cnt) < hayLen && cnt < needLen){ // 两个条件避免溢出
            if(needle.charAt(cnt) == haystack.charAt(i+cnt)) cnt++; //顺序比较
            else {
                i++; //找到不匹配从下一个haystack位置开始
                cnt = 0;
            }
        }
        if(cnt==needLen) return i;
        return -1;
    }

再有O(N)的方法就要用KMP算法了,看了几篇文章发现思路好懂,大致思路在找到不匹配的时候haystack位置不是增加1,而是增加另一个数,这个数由needle的特点决定,包括needle里面的char对称部分。code不好写,写出来没这个简便易懂,我就不误人子弟了,大家有兴趣自己搜搜吧。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值