问题描述:
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"
思路:
其实这道题的思路是非常多的,LeetCode上有许多方法可以参考;我选择了动态规划的方法实现。这里给出最重要的转移条件:
以上公式中,i,j代表在输入字符串s中的索引,state[i][j]说明i,j之间的字符串是否为回文字符串。其实具体编程实现的时候还是比较简单的,不过其中的逻辑却不好说,最好的方法是结合程序的把流程画一画:
本图主要是看右下角的圆框。我们让i,j都从左到右遍历(程序中i>=j),也就是从短到长地搜寻子回文字,整个过程其实把所有的。能都已经遍历了。
代码如下:
class Solution {
public:
string longestPalindrome(string s) {
const int str_len = s.size();
vector<vector <bool> > state_map(str_len, vector<bool>(str_len, false));
int start = -1;
int max_len = 0;
for (int i = 0; i < str_len; i++){
for (int j = 0; j <= i; j++){
if (i == j){
state_map[i][j] = true;
}
else if (i - j == 1){
state_map[i][j] = s[i] == s[j];
}
else{
state_map[i][j] = s[i] == s[j] && state_map[i - 1][j + 1];
}
if (state_map[i][j] && max_len < (i - j + 1)){
start = j;
max_len = i - j + 1;
}
}
}
return s.substr(start, max_len);
}
};