#include <iostream>
#include <vector>
#include <string>
class Solution{
public:
std::vector<int> getIndexofMax(std::string &input)
{
std::vector<int> result;
for(int i = 0;i<input.size();i++)
{
result.push_back(getIndexofMaxCore(input, i));
}
return result;
}
int getIndexofMaxCore(std::string &input, int index)
{
int length = 1;
int maxIndex = 0;
if(index == 0)
{
return -1;
}
while(length < index)
{
if(input.substr(0,length) == input.substr(index - length, length))
{
maxIndex = length;
}
length++;
}
return maxIndex;
}
int KMP(std::string &s1, std::string &s2) //s1为父字符串,s2为子字符串
{
std::vector<int> next = getIndexofMax(s1);
int lenOfS1 = 0;
int lenOfS2 = 0;
while(lenOfS2 < s1.size() && lenOfS2 < s2.size())
{
if(s1[lenOfS1] == s2[lenOfS2])
{
lenOfS1++;
lenOfS2++;
}
else
{
if(lenOfS2 == 0)//最长前缀已经没有了,s1从下一位再开始重新匹配
{
lenOfS1++;
}
else
{
lenOfS2 = next[lenOfS2];
}
}
}
return lenOfS2 == s2.size() ? lenOfS1 - lenOfS2 : -1;
}
private:
};
int main()
{
std::string s1 = "ababcababtkusfas";
std::string s2 = "btk";
std::cout<<Solution().KMP(s1, s2)<<std::endl;
// std::vector<int> output = Solution().getIndexofMax(s1);
//for(int i = 0;i<output.size();i++)
//{
// std::cout<<output[i]<<std::endl;
//}
//std::cout<<Solution().getIndexofMaxCore(s1,6)<<std::endl;
return 0;
}
KMP算法
最新推荐文章于 2023-01-23 18:57:44 发布