5. Longest Palindromic Substring
阿新 • • 發佈:2017-11-29
put fin pan col solution spa you subst nbsp
Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.
Example:
Input: "babad" Output: "bab" Note: "aba" is also a valid answer.
尋找最長回文字符串。
用動態規劃。dp[i][j]記錄從s[i]到s[j]是否為回文。
class Solution { public: string longestPalindrome(string s) {int len = s.length(); vector< vector<int> > dp(len, vector<int>(len)); string res; for( int i=0; i<len; ++i ){ for( int j=i; j>=0; --j ){ dp[i][j] = ((s[i]==s[j]) && (i-j<2 || dp[i-1][j+1])); if( dp[i][j] && (i-j+1)>res.length() ) res = s.substr(j, i-j+1);; } } return res; } };
5. Longest Palindromic Substring