您的位置:首页 > 其它

LeetCode:Implement strStr()

2016-06-04 20:24 267 查看


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 Tags
 Two Pointers String

Hide Similar Problems
 (H) Shortest Palindrome

思路:

KMP算法

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];
}
}
}

};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: