题目

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;
    }
}

2026.8.21

再来复习,以为自己熟悉2 pointers了但是这题不是那么标准的2 pointers就掉进坑里了。刚开始写了俩while,结果发现这个case过不去:

haystack = "mississippi"
needle = "issip"

因为真正的match issip的时候,前面的i在第一次我match issi的那段,然后因为我一直在移动haystack里的指针,所以发现第一个issi后面接的不是p以后,我又接着移,就没法考虑进最后那个i其实是真正match的第一个字符。

然后折腾出来一个nested while的解法,又掉进了haystack长度的坑,这个就好解决,改了一下终于过了。看了这篇笔记,又开始折腾for的写法,结果又掉进长度的坑里了。脑子不转了。下次还是得复习,别又进同一个坑了。

Logo

一站式 AI 云服务平台

更多推荐