https://leetcode-cn.com/problems/longest-palindromic-substring/
给定一个字符串 s,找到 s 中最长的回文子串。你可以假设 s 的最大长度为 1000。
示例 1:
输入: “babad”
输出: “bab”
注意: “aba” 也是一个有效答案。
示例 2:
输入: “cbbd”
输出: “bb”
超时的一个解法:
执行用时 :1016 ms, 在所有 C++ 提交中击败了5.03%的用户
内存消耗 :8.7 MB, 在所有 C++ 提交中击败了95.90%的用户
class Solution {
public:
string longestPalindrome(string s) {
int maxLen = 0;
string ret = "";
int pos_s = 0;
int k = 0;
int cnt = 0;
int len = s.size();
if (len < 1) {
return ret;
}
for (int j = 0; j < len; j++) {
for (int i = len -1; i >= 0; i--) {
k = 0;
cnt = i - j + 1;
while ((j + k < len) && (i - k >= 0) && (cnt >= 0)) {
if ((s[j + k] != s[i - k])) {
break;
}
k++;
}
if ((k > maxLen) && (cnt == k)) {
maxLen = k;
pos_s = j;
if (maxLen > len/2) {
j = len;
break;
}
}
}
}
ret = s.substr(pos_s, maxLen);
return ret;
}
};
其他用户解法:
执行用时 :112 ms, 在所有 C++ 提交中击败了50.28%的用户
内存消耗 :8.7 MB, 在所有 C++ 提交中击败了96.00%的用户
class Solution {
public:
string longestPalindrome(string s) {
const int n = s.size();
if(n < 2) return s;
int xs = 0, xe = 0;
int dp[n] = {0, };
for(int j = 0; j < n; ++j){
for(int i = 0; i < j; ++i){
if(!(dp[i] = dp[i + 1] || s[i] != s[j]) && (xe - xs) <= (j - i))
xs = i, xe = j;
}
}
return s.substr(xs, xe - xs + 1);
}
};