1 题目
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"
2 尝试解
2.1 分析
给定一个字符串,寻找其中最长回文子串。
暴力解法,可以以每个字符为中心向外扩展,中心可以有任意多个相同字符,即可以扩展直到两侧都没有相同的中心字符后,开始检查左右两侧是否相同。如果是,继续向左右各扩展一位,否则停止。比较当前回文串S与存储的结果result,如果S比result更长,更新result。
2.2 代码
class Solution {
public:
string longestPalindrome(string s) {
if(s == "") return s;
string result = "";
result = result + s[0];
for(int i = 0 ; i < s.size(); i++){
int left = i;
int right = i;
//there can be as many as possible same chars in center
while(left > 0 && s[left-1]==s[i]){
left--;
}
while(right < s.size()-1 && s[right+1]==s[i]){
right++;
}
if(left > 0 && right < s.size()-1)
{
while(s[left-1]==s[right+1]){ //then there can be pairs on both side
left--;
right++;
if(left == 0 ||right==s.size()-1) {break;}
}
}
if(right-left+1 > result.size()) {
result = s.substr(left,right-left+1);
}
}
return result;
}
};
3 标准解
3.1 分析
动态规划法:
使用布尔矩阵record[i][j]记录子串[i,j]是否为回文串,则record[i][j] = s[i]==s[j] && (j-i < 3 || record[i+1][j-1])。这是一个自底向上的动态规划,子问题中i增大,j减小,所以循环时,i从s.size()到0递增,j从i到s.size()递减,才能保证每次循环时,record[i+1][j-1]已经确定。
3.2 代码
class Solution {
public:
string longestPalindrome(string s) {
string result = "";
vector<vector<bool>> record(s.size(),vector<bool>(s.size(),false));
for(int i = s.size()-1; i>=0;i--){
for(int j = i; j < s.size();j++){
record[i][j] = s[i]==s[j] &&(j-i<3 || record[i+1][j-1]);
if(record[i][j]&& j-i+1 > result.size())
result = s.substr(i,j-i+1);
}
}
return result;
}
};