Implement strStr()
我的思路:
1、实现字符串匹配算法。
2、我知道比较出名的是KMP算法,在算法导论上有。
3、思路是先算出needle字符串中相同前缀后缀的长度,然后在主函数中依据这个信息来加速匹配过程。
class Solution {
public:
int strStr(char *haystack, char *needle) {
int hlen = strlen(haystack);
int nlen = strlen(needle);
int i = 0, j = 0;
int *next = new int[nlen];
GetNext(needle, next);
while (i < hlen && j < nlen) {
if (j == -1 || haystack[i] == needle[j]) {
i++;
j++;
}
else
j = next[j];
}
if (j == nlen)
return i - j;
return -1;
}
private:
void GetNext(char *p, int *next) {
int j = -1;
int i = 0;
int len = strlen(p);
next[0] = -1;
while (i < len - 1) {
if (j == -1 || p[j] == p[i]) {
++i;
++j;
next[i] = j;
}
else
j = next[j];
}
}
};