【LeetCode5】最长回文子串

LC5.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"

状态转移方程
dp[i][j] = dp[i + 1][j - 1], s[i] == s[j]
dp[i][j] = 0, s[i] != s[j]

dp[i][j]代表s[i] 到 s[j]是否为回文

public String longestPalindrome(String s) {
        //最长回文串的起点
        int start = 0;
        //最长回文串的长度
        int maxLength = 0;
        int length = s.length();
        boolean[][] dp = new boolean[length][length];
        for (int i = 0 ; i < length ; i++){
     	    // 判断从j 到 i 的回文情况
            for (int j = 0 ; j <= i; j++){
                // i - j < 2 包含了 i == j , i - j = 1的情况
                // 这两种情况下直接判断,不用判断dp[j + 1][i - 1]
                if (i - j < 2){ 
                    if (s.charAt(i) == s.charAt(j)){
                        dp[j][i] = true;
                    }
                }else{
                    if (s.charAt(i) == s.charAt(j) && dp[j + 1][i - 1]){
                        dp[j][i] = true;
                    }
                }
                if (i - j + 1 > maxLength && dp[j][i]){
                    maxLength = i - j + 1;
                    start = j;
                }
            }
        }
        return s.substring(start, start + maxLength);
    }

你可能感兴趣的:(Leetcode,LeetCode)