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"

 

 

Solution:

Dynamic programming

2D boolean n*n array, n is the length of the input string

Check palindrome: (1) head and tail are the same  (2) inner word is a palindrome

class Solution {
    public String longestPalindrome(String s) {
        int n = s.length();
        
        if (s == null || n < 2) {
            return s;
        }
        
        boolean[][] isPalindrome = new boolean[n][n];
        int left = 0;
        int right = 0;
        
        for (int j = 1; j < n; j++) {
            for (int i = 0; i < j; i++) {
                boolean isInnerWordPalindrome = isPalindrome[i + 1][j - 1] || j - i <= 2;
                
                if (s.charAt(i) == s.charAt(j) && isInnerWordPalindrome) {
                    isPalindrome[i][j] = true;
                    
                    //update longest palindrome
                    if (j - i > right - left) {
                        left = i;
                        right = j;
                    }
                }
            }
        }
        
        return s.substring(left, right + 1);
    }
}

Time complexity: O(n^2)

Space complexity: O(n^2)

Leave a comment