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;
}
}
};