Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.
Example:
Input: "babad" Output: "bab" Note: "aba" is also a valid answer.
Example:
Input: "cbbd" Output: "bb"
Personal tips: Manacher算法,保存回文开始位置和回文长度。
class Solution {
public:
string longestPalindrome(string s) {
int n = s.size(), len = 0, start = 0;
for (int i = 0; i < n; i++) {
int left = i, right = i;
while (right < n && s[right + 1] == s[right]) right++;
i = right;
while (left > 0 && right < n - 1 && s[left - 1] == s[right + 1]) {
left--;
right++;
}
if (len < right - left + 1) {
len = right - left + 1;
start = left;
}
}
return s.substr(start, len);
}
};
本文介绍了一种高效算法来找出给定字符串中的最长回文子串。通过迭代检查每个字符为中心的回文情况,该算法能有效找到最长的回文子串。文章通过实例演示了如何使用该算法解决问题。
500

被折叠的 条评论
为什么被折叠?



