[LeetCode] Longest Palindromic Substring
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"
以下说明转载自:
https://leetcode.com/problems/longest-palindromic-substring/discuss/147548/Direct-c%2B%2B-DP
My code is based on the solution Approach3.
First initialize a matrix P, which is used to store if the substring is palindromic. Now we should fill the block of "S(i) = S(i)" and "S(i) = S(i+1)", the basic case that we can't find any substring in it. Then with this matrix, we can decide if a string is palindromic by if its substring is palindromic and if its start letter equals end letter.
The image below is a matrix for string "abbc". For example, start with the first "b" and end with "c" tells if substring "bbc" is palindromic. What we need to do next is filling the "??" block, only half of the matrix is used.
After initialization, we can decide if a string is palindromic by its substring and newly added letters, shown below.
If we want to decide the block pointed by the arrow("abb"), we should look up [b,b], which is substring "b", and see if ("a"=="b"). As shown, "a"!="b", so "abb" is not palindromic.
After that, it seems like this:
Last, we have got this matrix, but we still need to find which is the longest palindromic substring.
My method is only traversing it, return the longest substring. So the result in this example is "bb".
class Solution {
public:
string longestPalindrome(string s) {
int len = s.size();
if (len == 0) return "";
bool** symbol = new bool*[len];
for (int i = 0; i < len; i++)
symbol[i] = new bool[len];
for (int i = 0; i < len; i++)
for (int j = 0; j < len; j++)
symbol[i][j] = false;
// initialize symbol[len][len]
for (int i = 0; i < len; i++) {
symbol[i][i] = true;
if (i == len - 1) break;
symbol[i][i+1] = (s[i] == s[i+1]);
}
// dynamic programming
for (int i = len - 2; i >= 0; i--) {
int start = i + 2;
for (int j = start; j < len; j++) {
symbol[i][j] = (symbol[i+1][j-1] && s[i] == s[j]);
}
}
// get max length string
int max = 0;
string maxstr = "";
for (int i = 0; i < len; i++) {
int count = 0;
for (int j = i; j < len; j++) {
if (symbol[i][j] == true) {
count = j - i + 1;
}
}
if (count > max) {
max = count;
maxstr = s.substr(i, count);
}
}
return maxstr;
}
};