题目:
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"
分析:
题目让输出最长回文子串,最容易想到的方法是:
以每一个元素或每两个相邻元素为中心向两端延伸,记录曾今出现过的最长的回文串,时间复杂度为O(n^2)
还有一种算法能线性时间内解决问题,但是不太理解,这里先不介绍
代码:
class Solution {
public:
string longestPalindrome(string s) {
string temp, result;
for (int i = 0; i < s.size(); ++i) {
temp = maxPalindrome(s, i, i);
if (temp.size() > result.size()){
result = temp;
}
temp = maxPalindrome(s, i, i+1);
if (temp.size() > result.size()){
result = temp;
}
}
return result;
}
string maxPalindrome(const string& s, int left, int right) {
while (left >= 0 && right < s.size()) {
if (s.at(left) != s.at(right)) {
break;
}
-- left;
++ right;
}
return s.substr(left + 1, right - left - 1);
}
};