[LeetCode]Longest Palindromic Substring

Given a string S, find the longest palindromic substring in S. You may assume that the maximum length of S is 1000, and there exists one unique longest palindromic substring.

思考:遍历求每个字符的左右延伸的最长字符串。

class Solution {

public:

    string compare(string s,int left,int right)

    {

        while(left>=0&&right<s.size())

        {

            if(s[left]==s[right])

            {

                left--;

                right++;

            }

            else break;

        }

        return s.substr(left+1,right-left-1);

    }

    string longestPalindrome(string s) {

        int len=0;

        int maxlen=0;

        string ans,res;

        for(int i=0;i<s.size();i++)

        {

            ans=compare(s,i,i);

            if(ans.size()>res.size()) res=ans;

            ans=compare(s,i,i+1);

            if(ans.size()>res.size()) res=ans;

        }

        return res;

    }

};

 网上有个更好的Manacher算法,只要O(n):

http://leetcode.com/2011/11/longest-palindromic-substring-part-ii.html

http://www.felix021.com/blog/read.php?2040

class Solution {

public:

	string preProcess(string s) 

	{  

		int n = s.length();  

		if (n == 0) 

			return "^$";  

		string ret = "^";  

		for (int i = 0; i < n; i++)    

			ret += "#" + s.substr(i, 1);   

		ret += "#$";  return ret;

	} 

	string longestPalindrome(string s) {

		// IMPORTANT: Please reset any member data you declared, as

        // the same Solution instance will be reused for each test case.

		string T = preProcess(s);  

		int n = T.length();  

		int *P = new int[n];  

		int C = 0, R = 0;  

		for (int i = 1; i < n-1; i++) 

		{    

			int i_mirror = 2*C-i; // equals to i' = C - (i-C)        

			P[i] = (R > i) ? min(R-i, P[i_mirror]) : 0;        

			// Attempt to expand palindrome centered at i    

			while (T[i + 1 + P[i]] == T[i - 1 - P[i]])      

				P[i]++;     

			// If palindrome centered at i expand past R,    

			// adjust center based on expanded palindrome.    

			if (i + P[i] > R) 

			{      

				C = i;      

				R = i + P[i];    

			}  

		}   

		// Find the maximum element in P.  

		int maxLen = 0;  

		int centerIndex = 0;  

		for (int i = 1; i < n-1; i++) 

		{    

			if (P[i] > maxLen) 

			{      

				maxLen = P[i];      

				centerIndex = i;    

			}  

		}  

		delete[] P;    

		return s.substr((centerIndex - 1 - maxLen)/2, maxLen);

	}

};

  

你可能感兴趣的:(substring)