Implement strStr()
Implement strStr().
Returns a pointer to the first occurrence of needle in haystack, or null if needle is not part of haystack.
写了好几种求next数组的方法,都可以通过。
class Solution {
public:
char *strStr(char *haystack, char *needle) {
int l_need = strlen(needle);
if(l_need == 0) return haystack;
int l_hay = strlen(haystack);
if(l_hay == 0) return NULL;
int idx = match(haystack, needle, l_hay, l_need);
if(idx >= 0)
return haystack+idx;
return NULL;
}
int match(char* s, char* p, int ls, int lp)
{
vector<int> next(lp);
int i = 0;
int j = 0;
getnext3(p, lp, next);
while(i < strlen(s))
{
if(-1 == j || s[i] == p[j])
{
++i;
++j;
}
else
j = next[j];
if(j == lp)
return i - lp;
}
return -1;
}
void getnext1(const char* p, int lp, vector<int>& next)
{
next[0] = -1;
int i = 0;
while(i < lp - 1)
{
int idx = i >= 0? next[i]: -1;
if(-1 == idx)
next[++i] = ++idx;
else if(p[i] == p[idx])
next[++i] = ++idx;
else
{
while(idx >= 0 && p[i] != p[idx])
idx = next[idx];
next[++i] = ++idx;
}
}
}
void getnext2(const char* p, int lp, vector<int>& next)
{
int j = 0, k = -1;
next[0] = -1;
while(j < lp - 1)
{
if(k == -1 || p[j] == p[k])
{
++j;
++k;
next[j] = k;
}
else
k = next[k];
}
}
void getnext3(const char*p, int lp, vector<int>& next)
{
next[0] = -1;
for(int i = 1; i < lp; ++i)
{
int idx = next[i-1];
if(-1 == idx)
next[i] = 0;
else if(p[i-1] == p[idx])
next[i] = ++idx;
else
{
while(idx >= 0 && p[i-1] != p[idx])
idx = next[idx];
next[i] = ++idx;
}
}
}
};