LeetCode 28. Implement strStr()

本文探讨LeetCode上的strStr()实现问题,通过对比两种方法:暴力匹配和KMP算法,详细解析了如何在haystack中寻找needle的首次出现位置。文章提供了优化后的暴力匹配代码,将运行时间从312ms降低到4ms,并讨论了KMP算法的基本思想。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目

Implement strStr().

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

Example 1:

Input: haystack = "hello", needle = "ll"
Output: 2

Example 2:

Input: haystack = "aaaaa", needle = "bba"
Output: -1

Clarification:

What should we return when needle is an empty string? This is a great question to ask during an interview.

For the purpose of this problem, we will return 0 when needle is an empty string. This is consistent to C's strstr() and Java's indexOf().


这道题是让你返回haystack中needle的位置,如果needle不是haystack的substring的话则返回-1,needle为空时返回0。这道题的普通思路很好想,就暴力遍历haystack看看有没有匹配的。我自己写的代码如下,运行时间312ms,只超越了20%的submission……

class Solution {
public:
    int strStr(string haystack, string needle) {
        if (needle == "")   return 0;
        bool found = true;
        for (int i = 0; i < haystack.length(); i++) {
            found = true;
            if (haystack[i] == needle[0]) {
                for (int j = 1; j < needle.length(); j++) {
                    if (haystack[i + j] != needle[j]) {
                        found = false;
                        break;
                    }
                }
                if (found) {
                    return i;
                }
            }
        }
        return -1;
    }
};

然而我这里用到的方法并不是最优雅的写法,主要有两个地方可以改进:

1. 在遍历heystack的时候不需要遍历整个字符串,只需要遍历到haystack.length() - needle.length()即可

2. 并不需要像我上面那样先判断首字母是否相同,可以直接开始比较,并且不需要设置bool found,可以直接判断j是否到达了needle的结尾(刚开始第一次就被found坑了,设完false以后忘记在重新回去遍历heystack的时候设回true导致一次匹配不成功后面的就算成功也只能返回-1)

改进后的代码如下,运行时间突然就缩短到了4ms:

class Solution {
public:
    int strStr(string haystack, string needle) {
        if (needle == "")   return 0;
        if (haystack.length() < needle.length())    return -1;
        for (int i = 0; i <= haystack.length() - needle.length(); i++) {
            int j;
            for (j = 0; j < needle.length(); j++) {
                if (haystack[i + j] != needle[j]) {
                    break;
                }
            }
            if (j == needle.length()) {
                return i;
            }
        }
        return -1;
    }
};

本来以为改一下很简单,结果提交了两次WA的……发现有几个坑在里面:

1. 需要提前判断haystack和needle的长度大小,如果needle比haystack还长那就直接返回-1,这个在我上面的写法中是不需要的

2. 在遍历haystack的时候,边界应该是<=而不是<,不然二者长度相等的情况就会被排除在外

另外一种神奇的方法就是我第一次听说的KMP算法(孤陋寡闻了),但是看了一些博客纷纷表示这道题的本意就是让你brute-force并不需要KMP,因为比较复杂而且代码比较难写,于是我就决定只了解KMP算法的思想,懒得去实现代码了orz(这个心态不对)。结果,发现看完一个视频和一篇文章后,还是完全不知道它在干什么……遂放弃,觉得这应该不是我目前的当务之急,等到把真·基础知识都补完了以后再回来填坑吧。

以下贴几个相关链接:

1. YouTube小哥的讲解:https://www.youtube.com/watch?v=BXCEFAzhxGY 视频时长一共17分钟,KMP正片开始是2:45,15分钟以后是分析算法复杂度的,因此其实讲解的一共只有12分钟,也不算太长吧orz(这个小哥前几天还看过他讲merge two sorted lists的题目,看了下他的视频有挺多都是讲算法的,感觉讲的还行,以后可以关注一下)

2. KMP in C++, explanation included:https://leetcode.com/problems/implement-strstr/discuss/12883/KMP-in-C%2B%2B-explanation-included 有代码也有解释,看起来还行

3. KMP算法详解:KMP算法详解 | Matrix67: The Aha Moments

4. C++ Brute-Force and KMP:https://leetcode.com/problems/implement-strstr/discuss/12956/C%2B%2B-Brute-Force-and-KMP


2025.3.18

随便第一页挑个easy只剩这个了,嗯,直接把题理解错了,implement出来一个别的东西……

还是只能brute force了但是和N年前比有进步。虽然还是掉进了判断长度的坑里,啊。

class Solution {
    public int strStr(String haystack, String needle) {
        for (int i = 0; i < haystack.length(); i++) {
            for (int j = 0; j < needle.length(); j++) {
                if (i + j >= haystack.length() || haystack.charAt(i + j) != needle.charAt(j)) {
                    break;
                }
                if (j == needle.length() - 1) {
                    return i;
                }
            }
        }
        return -1;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值