Implement strStr()

本文介绍了LeetCode上strstr函数的实现方法,通过简单的暴力搜索算法完成字符串匹配,并注意边界条件处理,避免越界错误。

原题链接: http://oj.leetcode.com/problems/implement-strstr/

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

这题据说用KMP算法会是线性时间复杂度,但KMP实现起来有点复杂。这里用了简单的brute force,复杂度O(mn)。 技巧是外层for循环只需要搜寻haystack-needle+1次。

已犯错误:

  1. i <= haystack.length() - needle.length()写成了<号。这种情况想想极端情形,haystack-needle==0的情况就理解了。
  2.  if(needle.length()==0) return 0; 这条件是leetcode的testcase要求的。
    复制代码
    public int strStr(String haystack, String needle) {
        if (needle.length() > haystack.length()) return -1;
        if(needle.length()==0) return 0;
        for (int i = 0; i <= haystack.length() - needle.length(); i++) {
            int needleIndex = 0;
            int haystackIndex = i;
            while (needle.charAt(needleIndex) == haystack.charAt(haystackIndex)) {
                needleIndex++;
                haystackIndex++;
                if (needleIndex == needle.length()) {
                    return haystackIndex - needleIndex;
                }
            }
        }
        return -1;
    }
复制代码

转载于:https://juejin.im/post/5a31341951882535cd4ad56b

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值