1.题目详情
Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.
给出一个字符串s,找到s中最长的一个回文串。可以假设s的最大长度为1000。
Example 1:
Input: “babad”
Output: “bab”
Note: “aba” is also a valid answer.
Example 2:
Input: “cbbd”
Output: “bb”
完善下面的代码:
class Solution {
public:
string longestPalindrome(string s) {
}
};
2.解题方法
回文串是指一个字符串的反转字符串还是和原来的一样,比如"aba"和"abba",即从中间看回文串是对称的。所以这里的解题思路就是从回文串的中间这一关键点落手。遍历字符串s,从每一处字符开始往两边看,找到以这处字符为中心的回文串。当然还要考虑特殊情况,像上面的"abba"的中间的两个’b’一样。
class Solution {
public:
string longestPalindrome(string s) {
int size = s.size();
int start = 0;
int maxLength = 0;
string maxLengthStr;
while (start < size) {
int left = start - 1;
int right = start + 1;
int length = 1;
while (s[left] == s[right] && left >= 0 && right < size) {
length = length + 2;
left = left - 1;
right = right + 1;
}
if (length > maxLength) {
maxLength = length;
maxLengthStr = s.substr(left + 1, right - left - 1);
}
length = 0;
left = start;
right = start + 1;
while (s[left] == s[right] && left >= 0 && right < size) {
length = length + 2;
left = left - 1;
right = right + 1;
}
if (length > maxLength) {
maxLength = length;
maxLengthStr = s.substr(left + 1, right - left - 1);
}
start = start + 1;
}
return maxLengthStr;
}
};
最终运行时间是8ms。