您的位置:首页 > 其它

Leetcode题解(九)

2015-12-10 19:00 537 查看

28、Implement strStr()-------KMP算法(*)

题目

这道题目其实就是实现KMP算法,并且该算法也是比较经典的算法,需要很好的掌握:

贴上几个介绍字符串匹配的算法说明链接

http://www.cnblogs.com/Su-30MKK/archive/2012/09/17/2688122.html

本题实现代码:

class Solution {
public:
int strStr(string haystack, string needle) {
if("" == needle)
return 0;
if("" == haystack )
return -1;

return kmp(haystack,needle);

}
int kmp(const std::string& s, const std::string& p, const int sIndex = 0)
{
std::vector<int>next(p.size());
getNext(p, next);//获取next数组,保存到vector中

int i = sIndex, j = 0;
while(i != s.length() && j != p.length())
{
if (j == -1 || s[i] == p[j])
{
++i;
++j;
}
else
{
j = next[j];
}
}

return j == p.length() ? i - j: -1;
}
void getNext(const std::string &p, std::vector<int> &next)
{
next.resize(p.size());
next[0] = -1;

int i = 0, j = -1;

while (i != p.size() - 1)
{
//这里注意,i==0的时候实际上求的是next[1]的值,以此类推
if (j == -1 || p[i] == p[j])
{
++i;
++j;
next[i] = j;
}
else
{
j = next[j];
}
}
}
};

 

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: