您的位置:首页 > 其它

[LeetCode]Implement strStr()

2015-07-22 21:24 423 查看
对KMP算法的一个很好的说明:KMP算法详解

下面是对算法的实现,有几点需要留意:
1,边界条件:needle的长度不能大于haystack
2,前条件:计算next数组,next的index代表字符串的长度;p 为haystack索引,q为needle索引。
3,循环结束条件,haystack和needle有一个遍历结束;
4,不变式:如果haystack[p] == needle[q], p++, q++; 否则,如果q>0, 则q = next[q]; 如果q == 0 , 则p++(q都已经指向needle第一个了还是不相等,只有p指向haystack的下一位了)
5,返回值:如果haystack没有被遍历完,说明needle遍历匹配完全;
如果haystack遍历完了,分两种情况;1,needle也遍历完,说明匹配;2,needle没有遍历完,没匹配。

class Solution {
public:
int strStr(string haystack, string needle) {
if (haystack.length() < needle.length()){
return -1;
}
vector<int> next;
next.push_back(0);
next.push_back(0);

//get next array
int j = 0;
for (int i = 1; i < needle.length(); ++i){
// j 在每次循环开始,都表示next[i]的值,同时也表示需要比较的下一个位置
while( j > 0 && needle[i] != needle[j])
j = next[j];
if (needle[i] == needle[j])
j++;
next.push_back(j);
}

// match
int p = 0;  // haystack index
int q = 0;  // needle index
while(p < haystack.length() && q < needle.length()){

if (haystack[p] != needle[q]){
if ( q > 0){
q = next[q];
}else{
p++;
}
}else{
p++;
q++;
}
}

if ( p < haystack.length()){
return p - needle.length();
}
if (q >= needle.length() && haystack[p-1] == needle[q-1]){
return p - needle.length();
}

return -1;
}
};


方法二:两次循环足矣

// java
public class Solution {
public int strStr(String haystack, String needle) {
for (int i = 0; ; i++){
for (int j = 0; ; j++){
if (j == needle.length()) return i;
if (i + j == haystack.length()) return -1;
if (needle.charAt(j) != haystack.charAt(i+j)) break;
}
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: