题目描述
题解
简单遍历匹配
class Solution {
public:
int strStr(string haystack, string needle) {
if (haystack.size() < needle.size()) return -1;
if (needle.size() == 0) return 0;
int i = 0;
int j = 0;
for (i = 0; i < haystack.size(); ++i) {
if (j == needle.size()) return i - j;
if (haystack[i] == needle[j]) j++;
else {
i -= j;
j = 0;
}
}
if (needle.size() == j) return i - j;
return -1;
}
};