LeetCode_28_实现strStr()
廖家龙 用心听,不照做

题目描述:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
实现 strStr() 函数。

给你两个字符串 haystack 和 needle ,请你在 haystack 字符串中找出 needle 字符串出现的第一个位置(下标从 0 开始)。如果不存在,则返回  -1 。

说明:当 needle 是空字符串时,我们应当返回什么值呢?这是一个在面试中很好的问题。对于本题而言,当 needle 是空字符串时我们应当返回 0 。这与 C 语言的 strstr() 以及 Java 的 indexOf() 定义相符。

示例:

输入:haystack = "hello", needle = "ll"
输出:2

输入:haystack = "aaaaa", needle = "bba"
输出:-1

输入:haystack = "", needle = ""
输出:0

提示:
1. 0 <= haystack.length, needle.length <= 5 * 10^4
2. haystack 和 needle 仅由小写英文字符组成

解法1:串的朴素模式匹配算法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
class Solution {
public:
int strStr(string haystack, string needle) {

int start = 0; //记录当前检查的子串起始位置
int i = 0, j = 0; //两个指针分别指向主串和模式串的开头

//这两行顺序不要颠倒
if (needle.size() == 0) return 0;
if (haystack.size() == 0) return -1;

while (i < haystack.size() && j < needle.size()) {

if (haystack[i] == needle[j]) {

++i;
++j;
} else {

++start;
i = start;
j = 0;
}
}

//可以发现:只要主串中含有模式串,最终j指针一定等于needle.size()
if (j == needle.size()) return start;
else return -1;
}
};

解法2:KMP算法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
class Solution {
public:

//求模式串needle的next数组
//当模式串的第j个字符匹配失败时,令模式串跳到next[j]再继续匹配
void get_next(string needle,int *next) {

int i = 0,j = -1;
next[0] = -1;

while (i < needle.size() - 1) {

if (j == -1 || needle[i] == needle[j]) {

++i;
++j;
next[i] = j;
} else j = next[j];
}
}

int strStr(string haystack, string needle) {

if (needle.size() == 0) return 0;
if (haystack.size() == 0) return -1;

int i = 0,j = 0;

int next[needle.size()];
get_next(needle,next); //得到模式串的next数组

int b = needle.size();
//这里必须写成:j < b,写成j < needle.size()运行结果为-1,不知道原因是啥❗️
while (i < haystack.size() && j < b) {

if (j == -1 || haystack[i] == needle[j]) {

++i;
++j;
} else j = next[j];
}

if (j == needle.size()) return i - j;
else return -1;
}

};