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”
Method 1:
Brute Force, Time
, timeout , space
class Solution {
public:
string longestPalindrome(string s) {
if(s.empty() || s.size() == 1)
return s;
int len = s.size(), maxlen = 0, start=0;
for(int i = 0; i < len; i++ )//子串的长度
{
for(int j =0; j< len - i; j++)//子串起始的位置
{
if(isPalindrome(s,i,j) && (i+1)>maxlen)
{
maxlen = i+1;
start = j;
}
}
}
return s.substr(start,maxlen);
}
private:
bool isPalindrome(string s ,int len ,int start)
{
int left = start, right = start + len;
while(left < right)
{
if(s[left] == s[right])
{
left ++;
right --;
}
else
return false;
}
return true;
}
};
Method 2: DP, time
,space
Reference: http://www.cnblogs.com/grandyang/p/4464476.html
This problem can also be solved by Dynamic Programming. The solution of the second splitting palindrome string in Palindrome Partitioning II is very similar. We maintain a Two-dimensional array dp, where dp[i][j] indicates whether the string interval [i, j] is a palindrome, when i = j, there is only one character, it must be a palindrome, if i = j + 1 , indicating that it is an adjacent character. At this time, it is necessary to judge whether s[i] is equal to s[j]. If i and j are not adjacent, that is, when i - j >= 2, in addition to judging s[i] and s[j] In addition to equality, if dp[j + 1][i - 1] is true, it is a palindrome. Through the above analysis, the recursion can be written as follows:
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
An interesting phenomenon here is that if I change the two-dimensional array in the following code from int to vector
class Solution {
public:
string longestPalindrome(string s) {
if(s.size() < 2)
return s;
int len = s.size(), maxlen = 0, start=0 ,end = 0;
int dp[len][len] = {0};//区间[i,j]
for(int i = 0; i < len; ++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] && i - j + 1 > maxlen)
{
maxlen = i - j + 1;
start = j;
end = i;
}
}
//dp[i][i] = 1;
}
return s.substr(start, end-start+1);
}
};
Method 3: Center Diffusion Method, Time ,space
class Solution {
string res="";//设置全局变量
public:
string longestPalindrome(string s) {
if(s.size() < 2)
return s;
for(int i = 0; i < s.size(); ++i)
{
helper(s,i,i);
helper(s,i,i+1);//无中心点,偶数情况
}
return res;
}
private:
void helper(string s ,int left, int right)
{
while(left >= 0 && right < s.size() && s[left] == s[right])
{
left --;
right ++;//中心扩散
}//跳出时,left+1到right-1为回文,
string cur = s.substr(left+1, right-left-1);//len=right-1-(left+1)+1=right-left-1
if(cur.size() > res.size())
res = cur;
}
};