leetcode 5 Longest Palindromic Substring

題目

https://leetcode.com/problems/longest-palindromic-substring/submissions/

思路

毫無疑問是動態(tài)規(guī)劃了。用二維數(shù)組dp[i][j]記錄從i下標到j下標是否為回文子串,則dp[i][j]取值有下面三種情況:

  • i==j,此時dp[i][j]=true
  • i+1=j,此時dp[i][j]=s[i]==s[j]
  • 其余情況,此時dp[i][j]取值為true的條件為:dp[i+1][j-1]=true并且s[i]==s[j]

根據(jù)條件直接遍歷len就好

代碼

    public String longestPalindrome(String s) {
        int length = s.length();
        boolean[][] isPal = new boolean[length][length];
        int maxLen = 0;// 記錄最長的長度
        String answer = ""; // 記錄最長的字符串

        // 遍歷子串的長度
        for(int len = 1; len <= length; len++) {
            for (int startIndex = 0; startIndex < length; startIndex++) {
                //計算起始位置并確保位置合法
                int endIndex = startIndex + len - 1;
                if (endIndex >= length) {
                    break;
                }
                // 核心邏輯
                isPal[startIndex][endIndex] = (len == 1)  // 長度為1
                        || (len == 2 && s.charAt(startIndex) == s.charAt(endIndex)) // 長度為2
                        || (isPal[startIndex + 1][endIndex - 1] && s.charAt(startIndex) == s.charAt(endIndex)); // 其他情況

                if (isPal[startIndex][endIndex] && len > maxLen) {
                    maxLen = len;
                    answer = s.substring(startIndex, endIndex + 1);
                }
            }
        }

        return answer;
    }
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

友情鏈接更多精彩內容