28. 实现 strStr()
class Solution {
public:
int* buildNext(string p){
int j=0, m = p.size(), *next = new int[m];
int t = next[0] = -1;
while(j < m-1){
if(0>t || p[j] == p[t]){
next[j+1] = t+1;
j++; t++;
}else
t = next[t];
}
return next;
}
int strStr(string t, string p) {
int n = t.size(), i=0;
int m = p.size(), j=0;
if(n==0&&m==0) return 0;
else if(n==0) return -1;
else if(m==0) return 0;
int* next = buildNext(p);
while(i<n && j<m){
if(0>j || t[i] == p[j])
{i++; j++;}
else
j=next[j];
}
delete[] next;
if(j==m) return i-j;
else return -1;
}
};
经典KMP,两个错误点:
* 不清楚如何判断匹配结果,如果模式串p的索引`j`到达末尾,说明匹配成功,然后`i-j`即为原串t的首个匹配点
* 空串的边界情况不知道怎么处理
PREVIOUSGolang
NEXTLeetcode - 双指针