作者
Ivan Chien
始于
分类:LeetCode
Tags: [ LeetCode ]
LeetCode 百题计划 - 5. Longest Palindromic Substring
始于
分类:LeetCode
Tags: [ LeetCode ]
LeetCode 百题计划 - 5. Longest Palindromic Substring
LeetCode 5. Longest Palindromic Substring
5. Longest Palindromic Substring
Difficulty: medium
这题叔之前发过, 记得是二维dp.
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”
但是那个二维dp的方法不记得了, 花了挺长时间写了一个记忆化的暴力:
1st Version:
class Solution {
public:
string longestPalindrome(string s) {
vector<vector<int>> dp(s.size(), vector<int>(s.size(), 0));
// dp[a][b]: ```true``` expresses s[a..b] is a palindromic substring;
// otherwise is not. assert a <= b.
int mx = -1;
string substr;
for (int i = 0; i < s.size(); i++) {
int a, b;
for (int delta = 0; delta < 2; delta++) {
a = b = i;
b += delta;
while (a >= 0 && b < s.size()) {
if (a + 1 <= b - 1 && dp[a+1][b-1] == 0) {
dp[a][b] = 0;
} else {
if (s[a] == s[b]) {
if (a + 1 <= b - 1) {
dp[a][b] = dp[a+1][b-1] + 2;
} else {
dp[a][b] = b - a + 1;
}
} else {
dp[a][b] = 0;
}
if (dp[a][b] > mx) {
mx = dp[a][b];
substr = s.substr(a, b - a + 1);
}
}
--a;
++b;
}
}
}
return substr;
}
};
Rate:
Runtime: 212 ms, faster than 18.62% of C++ online submissions for Longest Palindromic Substring.
Memory Usage: 194.1 MB, less than 5.23% of C++ online submissions for Longest Palindromic Substring.
194MB, 确实够暴力的了.
暂时没有心情去读讨论区的代码了, 之后再补.