Leetcode -- Implement strStr()

本文解析了LeetCode上一道关于字符串查找的问题,通过bruteforce方法实现,避免使用复杂的KMP算法,并提供了简洁易懂的代码示例。

问题链接:https://oj.leetcode.com/submissions/detail/17799169/

问题描述:Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.

问题API:  public int strStr(String haystack, String needle)

问题分析:其实网上有很多很牛逼的算法,比较常见的有KMP。但实际上我个人认为除非你是想秀操作,否则brute force就好,毕竟普通人类是不太可能在没有背过KMP算法的情况下临场构思出来。那些都是论文级别的算法,写出来就告诉面试官你是在背答案。

Brute force的算法实际也很简单,就是匹配haystack[i, i + 1, i + 2... i + needle.length() - 1] 和 needle[0, 1, 2... needle.length() - 1], 匹配不下去就i++,直到第一个匹配完整的就返回。

代码如下:

    public int strStr(String haystack, String needle) {
        if(needle == null || needle.length() == 0)
            return 0;
        if(haystack == null)
            return -1;
        for(int i = 0; i <= haystack.length() - needle.length(); i++){
            boolean found = true;
            for(int j = 0; j < needle.length(); j++){
                if(haystack.charAt(i + j) != needle.charAt(j)){
                    found = false;
                    break;
                }
            }
            if(found)return i;
        }
        return -1;
    }


评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值