[leetcode]5. Longest Palindromic Substring最长回文子串

时间:2021-11-08 18:24:14

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"

题意:

最长回文子串

Solution1:  Brute Force. We can run three loops, the outer two loops pick all substrings one by one by locking the corner characters, the inner loop checks whether the picked substring is palindrome or not.

[leetcode]5. Longest Palindromic Substring最长回文子串

[leetcode]5. Longest Palindromic Substring最长回文子串

code:

 /*
Time complexity: O ( n^3 ) outer->2 for loops to find all possible substrings;
inner->1 while loop to check current substring isValidPalindrome
Space complexity: O ( 1 )
*/ class Solution {
public String longestPalindrome(String s) {
String res = "";
for (int i = 0; i < s.length(); i++) {
for (int j = i ; j < s.length(); j++) {
String sub = s.substring(i, j + 1);
if (isValidPalindrome(sub) && sub.length() > res.length()) {
res = sub;
}
}
}
return res;
} public boolean isValidPalindrome(String s){
int l = 0;
int r = s.length() - 1;
while (l < r){
if(s.charAt(l) != s.charAt(r)){
return false;
}else{
l++;
r--;
}
}
return true;
}
}

Solution2:  DP.

step1, initialize a matrix for saving intermediate info

[leetcode]5. Longest Palindromic Substring最长回文子串

step2, we can pre-calculate some info(此题代码可以将预处理合并到general case中来写)

[leetcode]5. Longest Palindromic Substring最长回文子串

step3, To fill the matrix.  If  char at start != char at end,  then s.substring[start, end] cannot be a palindrom, fill 'F' in such spot

[leetcode]5. Longest Palindromic Substring最长回文子串

step4, To fill the matrix.  If  char at start == char at end, it means two sides are the same. Then if we can make sure substring [start + 1 to end - 1] is panlindrom,  the whole substring should be a panlindrom.

[leetcode]5. Longest Palindromic Substring最长回文子串

step5, to fill the matrix in the same way

[leetcode]5. Longest Palindromic Substring最长回文子串

[leetcode]5. Longest Palindromic Substring最长回文子串

step6, update the longest result

[leetcode]5. Longest Palindromic Substring最长回文子串

code

 class Solution {
public String longestPalindrome(String s) {
String res = "";
boolean[][] dp = new boolean[s.length()][s.length()];
int max = 0;
for(int j= 0; j < s.length(); j++){
for(int i = 0; i<=j; i++){
dp[i][j] = s.charAt(i) == s.charAt(j) && ((j-i<=2)||dp[i+1][j-1]);
if(dp[i][j] && (j-i+1>max)){
max = j- i + 1;
res = s.substring(i,j+1);
}
}
}
return res;
}
}