您的位置:首页 > 运维架构

Leetcode 28. Implement strStr()

2017-01-26 12:45 393 查看
Implement strStr().

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

思路:

1. 这个题很大陷阱。以为直接用two pointer,分别指向haystack和needle,比较是否相等,不等则指向needle的指针重新指向0位置。这里问题就是:needle可能有循环的情况产生,例如:

haystack=oproprops, needle=oprops


用上面的方法,haystack中opropr时,r!=s in needle,这时needle就要回到0位置,但实际上needle应该回到ops的位置,就因为needle是先后部分重合!所以,需要用o(mn)的方法来做。

2. 最优的方法是KMP,对needle做预处理,找到这种对称或重合的地方,复杂度o(m+n). 这个方法youtube有个视频讲解很清楚!!

//下面是**错误**的代码:
class Solution {
public:
int strStr(string haystack, string needle) {
//
int idx=0;i=0;
for(;i<haystack.size();i++){
if(idx==needle.size()) break;
if(haystack[i]==needle[idx]){
idx++;
}else
idx=0;
}
return idx==needle.size()?i-needle.size():-1;
}
};

//**正确**的方法:o(mn)需要在每个位置都检查后面的substr是否和needle相等。有很多重复的比较。所以最优的方法是kmp,o(m+n)
class Solution {
public:
int strStr(string haystack, string needle) {
//
int idx=0;i=0;
int nhay=haystack.size(),nneed=needle.size();
for(int i=0;i<=nhay-nneed;i++){
if(haystack.substr(i,nneed)==needle) return i;
}
return -1;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode twopointer