Leetcode-5 Longest Palindromic Substring (java)

Keywords: Programming Java

Longest Palindromic Substring

Original title

Given a string S, find the longest palindromic substring in S. You may assume that the maximum length of S is 1000, and there exists one unique longest palindromic substring

Topic translation

Given a string s, find the longest palindrome substring. Suppose the longest length of S is 1000, and there is a unique longest palindrome substring

Solutions

This problem can be solved by dynamic programming.
Assuming the length of the string is len, declare a two-dimensional array: dp = new boolean[len][len]
dp[i][j] identifies whether the substring of S[i~j] in string S is a palindrome string.
If S[i~j] is a palindrome string, two conditions must be satisfied:

  1. S[i] = S[j]
  2. dp[i+1][j-1] = true.

Code example Java

/**
 * Created by wks on 8/8/16.
 */
public class LongestPalindrome_5 {
    /**
     * Using the method of dynamic programming
     * @param s
     * @return
     */
    public static String longestPalindrome(String s){
        if (s == null || s.length() == 1) {
            return s;
        }

        int len = s.length();
        boolean[][] dp = new boolean[len][len];
        int begin = 0, end = 0, max = 1;

        for (int i = len - 1; i >= 0; i--){
            for (int j = i; j < len; j++){
                if (s.charAt(i) == s.charAt(j)){
                    if (j - i <= 2 ||  (dp[i+1][j-1] && j-1 > 0)){
                        dp[i][j] = true;
                        if (max < j - i + 1){
                            max = j - i + 1;
                            begin = i;
                            end = j;
                        }
                    }
                }
            }
        }


        return s.substring(begin, end+1);
    }

    public static void main(String[] args) {
        String str = "1aba12";
        long startTime = System.nanoTime();
        String palindrome = longestPalindrome(str);
        long endTime = System.nanoTime();
        long time = endTime - startTime;

        System.out.println("palindrome:" + palindrome + " time:" + time);
    }
}

Posted by besly98 on Wed, 13 Nov 2019 10:21:52 -0800