#include<iostream>
#include<string>
#include<stack>
using namespace std;
class Solution{
public:
void getNext(int* next, const string& s)
{
int j = 0;
next[0] = 0;
for (int i = 1; i < s.size(); i++)
{
while (s[i] != s[j] && j > 0) {
j = next[j - 1];
}
if (s[i] == s[j]) {
j++;
}
next[i] = j;
}
}
//统一减一
void getnext(int* next, const string& s) {
int j = -1;
next[0] = j;
for (int i = 1; i < s.size(); i++) {
while (s[i] != s[j+1] && j > -1) {
j = next[j];
}
if (s[i] == s[j+1])
{
j++;
}
next[i] = j;
}
}
int strStr(string haystack, string needle) {
if (needle.size() == 0) return 0;
int size = needle.size();
int* p =new int[size];
//int next[needle.size()];
getNext(p, needle);
int j = 0;
for (int i = 0; i < haystack.size(); i++) {
while (j > 0 && haystack[i] != needle[j]) {
j = p[j-1];
}
if (haystack[i] == needle[j])
{
j++;
}
if (j == needle.size()) {
return (i - needle.size() + 1);
}
}
return -1;
}
int strStr1(string haystack, string needle) {
if (needle.size() == 0) return 0;
int size = needle.size();
int* p = new int[size];
//int next[needle.size()];
getnext(p, needle);
int j = -1;
for (int i = 0; i < haystack.size(); i++) {
while (j >= 0 && haystack[i] != needle[j+1]) {
j = p[j];
}
if (haystack[i] == needle[j+1])
{
j++;
}
if (j == needle.size()-1) {
return (i - needle.size() + 1);
}
}
return -1;
}
};
void main()
{
string hay, need;
hay = "helloeeessaabaabaafdas";
need = "aabaaf" ;
Solution s;
cout<<s.strStr(hay,need)<<endl;
cout << s.strStr1(hay, need) << endl;
system("pause");
}
KMP实现
最新推荐文章于 2022-09-13 19:29:38 发布