您的位置:首页 > 其它

strstr实现(练习KMP算法的好例子)

2015-09-10 16:45 232 查看
solution 1.暴力破解

<span style="font-size:18px;">class Solution {
public:
int strStr(string haystack, string needle) {
int m = haystack.size();
int n = needle.size();
for(int i = 0; i <= m-n; i ++)
{
int j;
for(j = 0; j < n; j ++)
{
if(haystack[i+j] != needle[j])
break;
}
if(j == n)
return i;
}
return -1;
}
};
</span>


solution 2: KMP变形

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 = 0;
int j = 0;
while(i < hlen && j < nlen)
{
if(j == -1 || 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 -1;
}
void getNext(char *needle, int next[])
{// self match to contruct next array
int nlen = strlen(needle);
int j = -1;     // slow pointer
int i = 0;      // fast pointer
next[i] = -1;    //init next has one element
while(i < nlen-1)
{
if(j == -1 || 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
}
}
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: