Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.
Example 1:
Input: "babad"
Output: "bab"
Note: "aba" is also a valid answer.
Example 2:
Input:
"cbbd"
Output:
"bb"
class Solution {
public:
string longestPalindrome(string s) {
if (s.empty()) return "";
if (s.size() == 1) return s;
int min_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; // Skip duplicate characters.
i = k+1;
while (k < s.size()-1 && j > 0 && s[k + 1] == s[j - 1]) { ++k; --j; } // Expand.
int new_len = k - j + 1;
if (new_len > max_len) { min_start = j; max_len = new_len; }
}
return s.substr(min_start, max_len);
}
};
/*
string longestPalindrome(string s) {
if(s.size()==0) return s;
int res = 1;
string ans = s.substr(0, 1);
vector<vector<int>> dp(s.size(), vector<int>(s.size(), 0));
for(int i=0; i<s.size(); i++){
dp[i][i] = 1;
if( i < s.size()-1 && s[i] == s[i+1]){
dp[i][i+1] = 1;
ans = s.substr(i, 2);
}
}
for(int len = 3; len <= s.size(); len++)
for(int i=0; i<= s.size()-len; i++)
if(dp[i+1][i+len-2]==1 && s[i]==s[i+len-1]){
dp[i][i+len-1] = 1;
ans = s.substr(i, len);
}
return ans;
}
*/