KMP算法

#include 
#include 
#include 


class Solution{
public:
	std::vector getIndexofMax(std::string &input)
	{
		std::vector result;
		for(int i = 0;i 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< output = Solution().getIndexofMax(s1);
	//for(int i = 0;i

你可能感兴趣的:(C++,算法)