2D DP is an intuitive solution of course, but I got an MLE error, so I simplified it into a 1D DP:
class Solution { public: void goDp(vector<int> &dp, int &maxLen, int &is, int &ie, int startLen, int len, string &s) { for(int ilen = startLen; ilen < len; ilen += 2) for(int i = 0; i < len - ilen; i ++) { bool bEq = s[i] == s[i + ilen]; dp[i] = bEq ? (dp[i + 1] > 0 ? dp[i + 1] + 2 : 0) : 0; if( dp[i] > maxLen) { maxLen = dp[i]; is = i; ie = i + ilen; } } } string longestPalindrome(string s) { int len = s.length(); if(len == 0) return ""; int maxLen = -1; int is = 0, ie = 0; // Init vector<int> dp; dp.resize(len); // Starting from 2 for(int i = 0; i < len - 1; i ++) { if(s[i] == s[i + 1]) dp[i] = 2; else dp[i] = 0; if( dp[i] > maxLen) { maxLen = dp[i]; is = i; ie = i + 1; } } goDp(dp, maxLen, is, ie, 3, len, s); // Starting from 1 std::fill(dp.begin(), dp.end(), 1); goDp(dp, maxLen, is, ie, 2, len, s); return s.substr(is, ie - is + 1); } };
Since loop on current length n depends linearly on dp data with length n-1, we can use 1D DP. And there are two cases of odd\even lengthes.
LeetCode "Longest Palindromic Substring" - 1D DP
时间: 2024-10-28 11:43:54