Leetcode题解(九)

时间:2023-03-09 06:15:45
Leetcode题解(九)

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

题目

Leetcode题解(九)

这道题目其实就是实现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 ;
if("" == haystack )
return -; return kmp(haystack,needle); }
int kmp(const std::string& s, const std::string& p, const int sIndex = )
{
std::vector<int>next(p.size());
getNext(p, next);//获取next数组,保存到vector中 int i = sIndex, j = ;
while(i != s.length() && j != p.length())
{
if (j == - || s[i] == p[j])
{
++i;
++j;
}
else
{
j = next[j];
}
} return j == p.length() ? i - j: -;
}
void getNext(const std::string &p, std::vector<int> &next)
{
next.resize(p.size());
next[] = -; int i = , j = -; while (i != p.size() - )
{
//这里注意,i==0的时候实际上求的是next[1]的值,以此类推
if (j == - || p[i] == p[j])
{
++i;
++j;
next[i] = j;
}
else
{
j = next[j];
}
}
}
};