Leetcode No.28 Implement strStr()字串匹配(c++實現)
阿新 • • 發佈:2021-07-26
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
作者:雲夢士 出處:http://www.cnblogs.com/yunmeng-shi/ 本文版權歸作者和部落格園共有,歡迎轉載,但必須給出原文連結,並保留此段宣告,否則保留追究法律責任的權利。