Implement strStr()
Total Accepted: 109580
Total Submissions: 435297
Difficulty: Easy
Implement strStr().
Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
Subscribe to see which companies asked this question
Hide Similar Problems
思路:
c++ code:
class Solution {
public:
int strStr(string haystack, string needle) {
int i = 0;
int j = 0;
int sLen = haystack.length();
int pLen = needle.length();
int next[pLen];
getNext(needle, next);
while (i < sLen && j < pLen) {
//①如果j = -1,或者当前字符匹配成功(即S[i] == P[j]),都令i++,j++
if (j == -1 || haystack[i] == needle[j]) {
i++;
j++;
} else {
//②如果j != -1,且当前字符匹配失败(即S[i] != P[j]),则令 i 不变,j = next[j]
//next[j]即为j所对应的next值
j = next[j];
}
}
if (j == pLen)
return i - j;
else
return -1;
}
void getNext(string p, int next[]) {
int pLen = p.length();
int k = -1;
int j = 0;
next[0] = -1;
while (j < pLen) {
//p[k]表示前缀,p[j]表示后缀
if (k == -1 || p[k] == p[j]) {
k++;
j++;
next[j] = k;
} else {
k = next[k];
}
}
}
};