您的位置:首页 > 编程语言 > C语言/C++

leetcode_c++:Implement strStr() (028)

2016-08-05 19:42 495 查看
Implement strStr().

Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.

//在一个字符串中找到另一个字符串在其中的位置

//KMP

O(n)

class Solution {
public:
int strStr(string haystack, string needle) {
return strStrKMP(haystack, needle);
}
private:

// KMP
int strStrKMP(string haystack, string needle) {

if (needle.empty()){
return 0;
}
int i = 0;
int hSize = static_cast<int>(haystack.size());
int nSize = static_cast<int>(needle.size());
if (hSize < nSize){
return -1;
}
vector<int> next(nSize, -1);
calcNext(needle, next);
int j = 0;
while (i < hSize) {
if (j == -1 || haystack[i] == needle[j]){
i++;
j++;
}else{
j = next[j];
}
if (j >= nSize){
return i - nSize;
}
}
return -1;
}

void calcNext(const string& needle, vector<int> &next){
int nSize = static_cast<int>(needle.size());
int i = 0;
int j = -1;
while (i < nSize - 1) {
if (j == -1 || needle[i] == needle[j]){
i++;
j++;
next[i] = j;
}else{
j = next[j];
}
}
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: