Description:
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”分析:
从其中一个字符开始,左右向外扩展得到一个更长的子串,看是否是回文子串,如果是回文子串, 则继续向外遍历,直到遇到非回文子串或者超出子串范围。此方法的时间复杂度O(N^2);但是需要 注意针对一个字符向外扩张时,需要同时偶数字符个数回文子串和奇数字符个数回文子串两种情况。
class Solution {
public:
string longestPalindrome(string s) {
//边界条件
if (s.size() <= 1) {
return s;
}
string ret;
int start = 0, end = 0;
for (int i = 1; i < s.size(); ++i) {
// 偶数回文遍历的方式,abba这类回文从中心向两边遍历
start = i - 1;
end = i;
while (start >= 0 && end < s.size() && s[start] == s[end]) {
--start;
++end;
}
int paliStart = start + 1, paliEnd = end - 1;
int paliLen = paliEnd - paliStart + 1;
if (paliLen > ret.size()) {
ret = s.substr(paliStart, paliLen);
}
// 奇数回文遍历方式 abcba这种方式,中心点start=i-1, end = i+1
start = i - 1;
end = i + 1;
while (start >= 0 && end < s.size() && s[start] == s[end]) {
--start;
++end;
}
paliStart = start + 1;
paliEnd = end - 1;
paliLen = paliEnd - paliStart + 1;
if (paliLen > ret.size()) {
ret = s.substr(paliStart, paliLen);
}
}
return ret;
}
};