1. 题目
1.1 英文题目
Implement strStr().
Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
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().
1.2 中文题目
给定一个 haystack 字符串和一个 needle 字符串,在 haystack 字符串中找出 needle 字符串出现的第一个位置 (从0开始)。如果不存在,则返回 -1。
1.3输入输出
输入 | 输出 |
---|---|
haystack = "hello", needle = "ll" | 2 |
haystack = "aaaaa", needle = "bba" | -1 |
haystack = "", needle = "" | 0 |
1.4 约束条件
- 0 <= haystack.length, needle.length <= 5 * 104
- haystack and needle consist of only lower-case English characters.
2. 分析
2.1 Brute Force(暴力搜索)算法
class Solution {
public:
int strStr(string haystack, string needle) {
int ans = -1;
if (needle.size() == 0)
ans = 0;
if (haystack.size() >= needle.size())
for (unsigned int i = 0; i <= haystack.size() - needle.size(); i++)
for (unsigned int j = 0; j < needle.size() && haystack[i + j] == needle[j]; j++)
if (j == needle.size() - 1)
ans = i;
return ans;
}
};
2.2 KMP算法
算法解释可参考:
KMP字符串匹配算法2
从头到尾彻底理解KMP
代码如下:
class Solution {
public:
int strStr(string haystack, string needle) {
int m = haystack.size(), n = needle.size();
if (!n) {
return 0;
}
vector<int> lps = kmpProcess(needle);
for (int i = 0, j = 0; i < m;) {
if (haystack[i] == needle[j]) {
i++, j++;
}
if (j == n) {
return i - j;
}
if (i < m && haystack[i] != needle[j]) {
j ? j = lps[j - 1] : i++;
}
}
return -1;
}
private:
vector<int> kmpProcess(string needle) {
int n = needle.size();
vector<int> lps(n, 0);
for (int i = 1, len = 0; i < n;) {
if (needle[i] == needle[len]) {
lps[i++] = ++len;
}
else if (len) {
len = lps[len - 1];
}
else {
lps[i++] = 0;
}
}
return lps;
}
};
代码参考:https://leetcode.com/problems/implement-strstr/discuss/12956/C%2B%2B-Brute-Force-and-KMP