一、问题描述
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"
二、思路分析
分别以每个字母为中心,向两边展开,寻找最长的回文字符串,
有两种情况:1、该字符正好为中心;
2、该字符和右边的字符相同,构成中心。
三、代码
class Solution {
public:
string longestPalindrome(string s) {
int n = s.length();
if (n == 0) {
return "";
}
string longest = s.substr(0,1);
for (int i = 0; i < n-1; i++) {
string temp = findstr(s, i, i); //字符是s[i]为中心
if (longest.length() < temp.length()) {
longest = temp;
}
temp = findstr(s, i, i+1); //字符s[i]和s[i+1]为中心
if (longest.length() < temp.length()) {
longest = temp;
}
}
return longest;
}
private:
string findstr(string s, int l, int r) { //寻找以字符s[l]为中心的最长回文串
int n = s.length();
while (l >= 0&& r <= n-1&&s[l] == s[r]) {
l--;
r++;
}
return s.substr(l+1, r-l-1);
}
};