以前只求过最长公共子序列,用动态规划做。这道题的难点在如何判断是不是回文的,其实一旦中心确认了,就只要两边一点一点扩展即可,我分了两种情况,中心为一个字符与中心为两个字符,代码可能有点累赘。
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"来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/longest-palindromic-substring
class Solution {
public:
string longestPalindrome(string s) {
int len = s.size();
vector<float> centre1;
vector<float> centre2;
for (int i = 1; i < len - 1; i++) {
if (s[i - 1] == s[i + 1]) { centre1.push_back(i); }
}
for (int i = 1; i < len; i++) {
if (s[i - 1] == s[i]) { centre2.push_back(((float)2 * i - 1) / 2); }
}
if (centre1.size() == 0 && centre2.size() == 0) centre1.push_back(0);
int cnt = 0, max = 0, begin = 0;
for (int i = 0; i < centre1.size(); i++) {
float cent = centre1[i];
cnt = 1;
int k = 1;
while (cent - k >= 0 && cent + k < len && s[cent + k] == s[cent - k]) {
cnt += 2;
k++;
}
if (cnt > max) { max = cnt; begin = cent - k + 1; }
}
for (int j = 0; j < centre2.size(); j++) {
float cent = centre2[j];
cout << centre2[j] << endl;
cnt = 0;
int k = 0;
while (cent - 0.5 - k >= 0 && cent + 0.5 + k < len && s[cent + 0.5 + k] == s[cent - 0.5 - k]) {
cnt += 2;
k++;
}
if (cnt > max) { max = cnt; begin = cent - 0.5 - k + 1; }
}
string ans = s.substr(begin, max);
return ans;
}
};
执行用时 :36 ms, 在所有 cpp 提交中击败了78.20%的用户
内存消耗 :9.4 MB, 在所有 cpp 提交中击败了75.08%的用户