1. 概述
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"
根据这道题的题意可知,是需要求取一串字符串中的最长回文字符串。
2. 编码
2.1 暴力解法
class Solution {
public:
string longestPalindrome(string s)
{
if(s.length() <= 1)
return s;
string m_temp(s.rbegin(), s.rend());
if(m_temp == s) return s;
string max_str(""); //记录最长的回文
int str_len(s.length()); //字符串的长度
for(int i=0; i<str_len; i++)
{
if(str_len-i < max_str.length()) break;
for(int j=str_len-1; j>=0; j--)
{
if(s.at(i) != s.at(j)) continue;
string temp = s.substr(i, j+1-i);
if(temp.length() < max_str.length())
break; //截取到的子字符串小于了当前的最大回文字符串
else
{
if(cheack_str(temp))
{
if(temp.length() > max_str.length())
max_str = temp;
}
} //判断是不是回文
}
}
return max_str;
}
//检查是不是回文,是返回bool,否返回false
bool cheack_str(string str)
{
int str_len(str.length());
if(str_len <= 1) return true;
if(1 == (str_len%2))
{
string temp1(str.substr(0, (str_len-1)/2));
string temp2(str.substr((str_len-1)/2+1, (str_len-1)/2));
string temp3(temp2.rbegin(), temp2.rend());
if(temp1==temp3)
return true;
else return false;
} //奇数的长度
else
{
string temp1(str.substr(0, str_len/2));
string temp2(str.substr(str_len/2, str_len/2));
string temp3(temp2.rbegin(), temp2.rend());
if(temp1==temp3)
return true;
else return false;
} //偶数的长度
}
};
2.2 动态规划
维护一个二维数组dp,其中dp[i][j]表示字符串区间[i, j]是否为回文串,当i = j时,只有一个字符,肯定是回文串,如果i = j + 1,说明是相邻字符,此时需要判断s[i]是否等于s[j],如果i和j不相邻,即i - j >= 2时,除了判断s[i]和s[j]相等之外,dp[j + 1][i - 1]若为真,就是回文串,通过以上分析,可以写出递推式如下:
dp[i, j] = 1 if i == j
= s[i] == s[j] if j = i + 1
= s[i] == s[j] && dp[i + 1][j - 1] if j > i + 1
class Solution {
public:
string longestPalindrome(string s) {
int dp[s.size()][s.size()] = {0}, left = 0, right = 0, len = 0;
for (int i = 0; i < s.size(); ++i) {
for (int j = 0; j < i; ++j) {
dp[j][i] = (s[i] == s[j] && (i - j < 2 || dp[j + 1][i - 1]));
if (dp[j][i] && len < i - j + 1) {
len = i - j + 1;
left = j;
right = i;
}
}
dp[i][i] = 1;
}
return s.substr(left, right - left + 1);
}
};