leetcode:Longest Palindromic Substring



最长公共子字符串

定义状态dp[i][j],表示子字符串Si-Sj是否回文串

那么dp[i][j] = dp[i+1][j - 1] && s(i) == s(j)

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



你可能感兴趣的:(leetcode)