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 longestPalindrome(string s) { int len = s.length(); string ans = ""; for(int i=0;i<len;i++){ int ind = min(i, len-i-1), j=1; for(j=1;j<=ind;j++){ if(s[i-j] != s[i+j]){ break; } } string tmp = s.substr(i-j+1, 2*j-1); if(tmp.length() > ans.length()) ans = tmp; }
// assume the length is odd for(int i=0;i<len-1;i++){ if(s[i]==s[i+1]){ int ind = min(i, len-i-2), j=1; for(j=1;j<=ind;j++){ if(s[i-j] != s[i+1+j]){ break; } } string tmp = s.substr(i-j+1, 2*j); if(tmp.length() > ans.length()) ans = tmp; } }
//assume the length is even return ans; } };
时间: 2024-10-28 20:07:42