@[TOC](Leetcode 28. Implement strStr() 实现 strStr())
28. Implement strStr()
题目描述
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
解答
这道题是典型的KMP问题,没什么好说的,先建立一个KMP数组,然后对haystack做一遍处理就得到了答案。
代码
class Solution {
public:
int strStr(string haystack, string needle) {
vector<int> lps = KMP(needle);
if (needle.size() == 0)
return 0;
int j = 0;
int i = 0;
while (i < haystack.size()) {
if (haystack[i] == needle[j]) {
i++, j++;
}
if (j == needle.size()) {
return i - j;
}
if (i < haystack.size() && haystack[i] != needle[j]) {
if (j != 0) {
j = lps[j - 1];
} else {
i++;
}
}
}
return -1;
}
private:
vector<int> KMP(string needle) {
vector<int> lps(needle.size(), 0);
int len = 0;
for (int i = 1; i < needle.size();) {
if (needle[i] == needle[len]) {
lps[i ++] = ++len;
} else if (len != 0) {
len = lps[len - 1];
} else {
lps[i ++] = 0;
}
}
return lps;
}
};