Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.python
Example 1:c++
Input: "babad" Output: "bab" Note: "aba" is also a valid answer.
Example 2:code
Input: "cbbd" Output: "bb"
1.動態規劃來求解string
class Solution: def longestPalindrome(self, s): """ :type s: str :rtype: str """ res='' for i in range(len(s)): m=self.helper(s,i,i) if len(m)>len(res): res=m n=self.helper(s,i,i+1) if len(n)>len(res): res=n return res def helper(self,s,l,r): while l>=0 and r<len(s) and s[l]==s[r]: l-=1; r+=1; return s[l+1:r]
2. expand arround centerio
c++:class
class Solution { public: string longestPalindrome(string s) { if(s.empty()) return ""; if(s.size()==1) return s; int start=0,max_len=1; for (int i=0;i<s.size();){ if (s.size()-i<=max_len/2) break; int j=i,k=i; while(k<s.size()-1 && s[k+1]==s[k]) k++; i=k+1; while(k<s.size()-1 && j>0 && s[k+1]==s[j-1]){++k;--j;} int new_len=k-j+1; if(new_len>max_len){ start=j; max_len=new_len; } } return s.substr(start,max_len); } };
這裏跟動態規劃差很少 也是一一擴大,不過這裏進行了 重複值的識別,能夠將兩次求最大回文序列 變成一次求最大回文序列。im