首页 > 代码库 > Longest Palindromic Substring

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.

思路:找出字符串s中最长的回文子串。我们可以这样考虑,从中间向两边扩展,尽可能找出最长的回文子串。在此注意要考虑奇偶位置的比较,这一点要考虑清楚。

 

class Solution {public:    string Sub_Palindrome(string s,int left,int right)    {        int l=left,r=right;        int n=s.length();        while(l>=0 && r<=n-1 && s[l]==s[r])        {            l--;            r++;        }        return s.substr(l+1,r-l-1);    }    string longestPalindrome(string s) {        int n=s.length();        if(n==0)            return "";        string longest=s.substr(0,1);        for(int i=0;i<n-1;i++)        {            string sub_str1=Sub_Palindrome(s,i,i);//奇数            if(sub_str1.length()>longest.length())                longest=sub_str1;            string sub_str2=Sub_Palindrome(s,i,i+1);//偶数            if(sub_str2.length()>longest.length())                longest=sub_str2;        }        return longest;    }};