Leetcode5. Longest Palindromic Substring
题目:
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"
题意分析:刚开始看的时候想的是用遍历的方法闪现,但是提交的时候果然不出意料的timelimited,于是就想着修改算法。然后有了从中心遍历的想法,然后全局变量一个maxlen和begin。
代码如下:
class Solution {
public:
int maxlen = 0, begin = 0;
string longestPalindrome(string s) {
if (s.size() < 2) return s;
for (int i = 0; i < s.size(); i++) {
processPalindrome(s, i, i);
processPalindrome(s, i, i + 1);
}
return s.substr(begin, maxlen);
}
void processPalindrome(string s, int j, int k) {
while (j >= 0 && k < s.size() && s[j] == s[k]) {
j--; k++;
}
if (maxlen < k - j - 1) {
begin = j + 1;
maxlen = k - j - 1;
}
}
};
本文介绍了一种高效求解LeetCode 5题——最长回文子串的有效算法。通过中心扩展法避免了时间限制问题,实现代码简洁高效。文中详细解释了如何从字符串的每个字符出发,向两边扩展寻找回文子串的过程。
593

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



