leetcode 5. Longest Palindromic Substring(回文和Manacher算法)

关于回文问题的解法

题目地址在这里

#include<string>
#include<algorithm>
#include<new>
#include<iostream>
using namespace std;

string addS(const string& s) {
	string temp;
	for(int i=0; i<s.size(); ++i) {
		temp+='#';
		temp+=s[i];
	}
	temp+='#';
	return temp;
}
string castS(const string& s) {
	string ans;
	for(int i=0; i<s.size(); ++i) {
		if(s[i]=='#');
		else ans+=s[i];
	}
	return ans;
}

string longestPalindrome(string s) {
	if(s.empty()||s.size()==1)return s;
	cout<<"original string is:"<<s<<endl;
	string temp=addS(s);
	cout<<"after adding #, string is :"<<temp<<endl;
	int maxlen=0,id=0;
	int ms[2];
	auto sz=temp.size();
	int *p=new int[sz]();
	
	for(int i=1; i<sz; ++i) {
		if(p[id]+id>i)p[i]=min(p[id*2-i],p[id]-i+id);
		else p[i]=1;
		while(i+p[i]<sz&&i-p[i]>=0&&temp[i+p[i]]==temp[i-p[i]])++p[i];
		if(p[id]+id<i+p[i])id=i;
		if(maxlen<p[i]) {
			maxlen=p[i]-1;
			ms[0]=i-maxlen;
			ms[1]=i+maxlen;
		}
	}
	cout<<"ms[0]和ms[1]: "<<ms[0]<<" "<<ms[1]<<endl;
	string temp1(temp.begin()+ms[0],temp.begin()+ms[1]);
	cout<<"temp1 is:"<<temp1<<endl; 
	string ans=castS(temp1);
	delete []p;
	return ans;
}

int main(){
	string ans=longestPalindrome("aa");
	cout<<ans<<endl;
	cout<<ans.size();
}


猜你喜欢

转载自blog.csdn.net/duangyhn/article/details/77528606