题目:
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"
解题思路:题目要求的是最长回文子序列。而这种序列,从它的中心点的地方开始,往左和往右依次读的字符,每个都一样。依据这个特征,我们可以判断一个序列是不是回文子序列。我的解题思路就是,找到一个中心点,然后从它开始向左向右拓展,直到找到它完整的一串回文子序列。然后,接下来的事就简单了,将这个子序列的大小和当前记录的最大子序列的大小相比,并且记录些最大子序列的长度和内容。
代码如下:
class Solution {
public:
string longestPalindrome(string input) {
int count = 0, max = 0;
string longest;
for (int i = 1; i < input.length(); i++) {
if (i+1 < input.length()) {
if (input[i-1] == input[i+1]) {
for (int j = 0 ; ;j++) {
if (i-1-j <0 || i+1+j >= input.length()) {
break;
}//防止数组越界
if (input[i-1-j] == input[i+1+j]) {
count++;
} else {
break;
}
}
if (count >= max) {
max = count;
longest = "";
for (int k = 0; k < 2*count+1; k++) {
longest = longest+input[i-count+k];
}
}
count = 0;
}
}
if (input[i-1] == input[i]) {
for (int j = 0 ; ;j++) {
if (i-1-j <0 || i+j >= input.length()) {
break;
}//防止数组越界
if (input[i-1-j] == input[i+j]) {
count++;
} else {
break;
}
}
if (count > max) {
max = count;
longest = "";
for (int k = 0; k < 2*count; k++) {
longest = longest+input[i-count+k];
}
}
count = 0;
}
}
if (max == 0)
longest = longest+input[0];
return longest;
}
};