Implement strStr()
Implement strStr().
Returns a pointer to the first occurrence of needle in haystack, or null if needle is not part of haystack.
解法一:暴力解
class Solution {
public:
int strStr(string haystack, string needle) {
int m = haystack.size();
int n = needle.size();
for(int i = ; i <= m-n; i ++)
{
int j;
for(j = ; j < n; j ++)
{
if(haystack[i+j] != needle[j])
break;
}
if(j == n)
return i;
}
return -;
}
};
解法二:标准KMP算法。可参考下文。
(1)先对模式串needle做“自匹配”,即求出模式串前缀与后缀中重复部分,将重复信息保存在next数组中。
(2)依据next数组信息,进行haystack与needle的匹配。
class Solution {
public:
int strStr(char *haystack, char *needle) {
int hlen = strlen(haystack);
int nlen = strlen(needle);
int* next = new int[nlen];
getNext(needle, next);
int i = ;
int j = ;
while(i < hlen && j < nlen)
{
if(j == - || haystack[i] == needle[j])
{// match current position, go next
i ++;
j ++;
}
else
{// jump to the previous position to try matching
j = next[j];
}
}
if(j == nlen)
// all match
return i-nlen;
else
return -;
}
void getNext(char *needle, int next[])
{// self match to contruct next array
int nlen = strlen(needle);
int j = -; // slow pointer
int i = ; // fast pointer
next[i] = -; //init next has one element
while(i < nlen-)
{
if(j == - || needle[i] == needle[j])
{
j ++;
i ++; //thus the condition (i < nlen-1)
next[i] = j; //if position i not match, jump to position j
}
else
{
j = next[j]; //jump to the previous position to try matching
}
}
}
};