leet-code、实现strStr():https://leetcode-cn.com/problems/implement-strstr/
ソリューション1ダブルポインター
ダブルポインターO(m + n)
は、haystackのすべての文字を先頭としてトラバースします
0 ms 6.9 MB
class Solution {
public:
int strStr(string haystack, string needle) {
if (needle.size() == 0) {
return 0;
}
if (haystack.size() < needle.size()) {
return -1;
}
size_t i = 0, j = 0;
int ret = -1;
while (i < haystack.size() && j < needle.size()) {
if (haystack[i] == needle[j]) {
if (ret == -1) {
ret = i;
}
++i; ++j;
} else {
if (ret != -1) {
j = 0;
// 回溯
i = ret + 1;
ret = -1;
} else {
++i;
}
}
}
// i-ret 如果不和 needle.size() 相等,则不存在
if ((i - ret) != needle.size()) {
ret = -1;
}
return ret;
}
};
解決策2マップを使用する
マップ
を使用して干し草の山を長さのneedle.size()の文字列に分割し、それをマップのキーとして保存し、2番目のパラメーターとしてインデックスを作成します
12 ms 8 MB
class Solution {
public:
int strStr(string haystack, string needle) {
if (needle.size() == 0) {
return 0;
}
if (haystack.size() < needle.size()) {
return -1;
}
map<string, size_t> m;
for (size_t i = 0; i <= haystack.size() - needle.size(); ++i) {
string key = haystack.substr(i, needle.size());
// 如果没有这个 key 才添加到 map 中(也就是说只返回第一次出现的位置)
if (m.find(key) == m.end()) {
m[key] = i;
}
}
if (m.find(needle) != m.end()) {
return m[needle];
}
return -1;
}
};
ソリューション3 KMP
TODO:まだ学習していません。