1. Longest Palindromic Substring. (LeetCode 5)
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"
class Solution { public String longestPalindrome(String s) { // corner case if (s == null){ return null; } String res = new String(); boolean[][] dp = new boolean[s.length()][s.length()]; // base case dp[s.length() - 1][s.length() - 1] = true; int globalLength = 1; res = s.substring(s.length() - 1, s.length()); for (int i = s.length() - 2; i >= 0; i--){//induction rule决定了必须从下往上,从中间往右填表 for (int j = i; j < s.length(); j++){ // case 1: a, aa, aba if ((s.charAt(i) == s.charAt(j)) && (j - i < 3)){ dp[i][j] = true; }else if((s.charAt(i) == s.charAt(j)) && (dp[i + 1][j - 1] == true)){ // case2: abba dp[i][j] = true; }else{ dp[i][j] = false; } if (dp[i][j] == true && j - i + 1> globalLength){ // update globalLength and res globalLength = j - i + 1; res = s.substring(i, j + 1); } } } return res; } } Time : O(n^3) Space: O(n^2)