您的位置:首页 > 其它

leetcode 28. Implement strStr()

2016-03-28 10:46 393 查看
1.题目

Implement strStr().

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

给你两个字符串haystack和needle,如果needle是haystack的子串,返回needle在haystack的起始位置,否则返回-1。

2.思路 

这道题考察的是字符串匹配的算法。

解法一:暴力解法。

class Solution {
public:
int strStr(string haystack, string needle) {
int a = haystack.size();
int b = needle.size();
if (b == 0) return 0;

int j;
for (int i = 0; i < a-b+1; i++) {
for (j = 0; j < b && haystack[i+j] == needle[j]; j++);
if (j == b) return i;
}

return -1;
}
};
解法二:KMP算法。

关于字符串匹配其他博客上有很详细的讲解,这里我先放上链接。http://www.cnblogs.com/c-cloud/p/3224788.html(个人感觉说的比较详细)

class Solution {
public:
// next数组的作用:当T失配时,next数组对应的元素知道应该用T串的哪个元素进行下一轮的匹配
vector<int> getNext(string T) {
int len = T.size();
vector<int> next(len);
int i = 0, j = -1; //i代表T的后缀,j代表T的前缀,其实是为了找出前后缀的最长公共长度
next[0] = -1;
while (i < len-1) {
if (-1 == j || T[i] == T[j]) {
i++; j++;
if (T[i] == T[j])
next[i] = next[j];
else
next[i] = j;
}
else
j = next[j];
}
return next;
}
int kmp(string S, string T) {
int len1 = S.size(); // 注意此处不能用size_t声明,理由见@1
int len2 = T.size();
if (len2 == 0) return 0;
vector<int> next(len2);
next = getNext(T);
int i = 0, j = 0;
while (i < len1 && j < len2) {
if (S[i] == T[j] || -1 == j ) { // 为什么此处j会等于-1呢?因为j可能为0,当s[0]!=T[0]时,j=next[0]=-1
i++; j++;
}
else
j = next[j];
if (j >= len2) return i - j; // @1 : 如果len2是用size_t声明的话,int j 总是大于 len2的
}
return -1;
}
int strStr(string haystack, string needle) {
return kmp(haystack, needle);
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息