diff --git a/problems/0647.回文子串.md b/problems/0647.回文子串.md index e172de54..084b9f74 100644 --- a/problems/0647.回文子串.md +++ b/problems/0647.回文子串.md @@ -304,7 +304,38 @@ class Solution { } } ``` +LeetCode 5. Longest Palindromic Substring(LeetCode 647. 同一題的思路改一下、加一點,就能通過LeetCode 5) +```java +class Solution { + public String longestPalindrome(String s) { + //題目要求要return 最長的回文連續子串,故需要記錄當前最長的連續回文子串長度、最終起點、最終終點。 + int finalStart = 0; + int finalEnd = 0; + int finalLen = 0; + char[] chars = s.toCharArray(); + int len = chars.length; + + boolean[][] dp = new boolean[len][len]; + for (int i = len - 1; i >= 0; i--) { + for (int j = i; j < len; j++) { + if (chars[i] == chars[j] && (j - i <= 1 || dp[i + 1][j - 1])) + dp[i][j] = true; + //和LeetCode 647,差別就在這個if statement。 + //如果當前[i, j]範圍內的substring是回文子串(dp[i][j]) 且(&&) 長度大於當前要記錄的最終長度(j - i + 1 > finalLen) + //我們就更新 當前最長的連續回文子串長度、最終起點、最終終點 + if (dp[i][j] && j - i + 1 > finalLen) { + finalLen = j - i + 1; + finalStart = i; + finalEnd = j; + } + } + } + //String.substring這個method的用法是[起點, 終點),包含起點,不包含終點(左閉右開區間),故終點 + 1。 + return s.substring(finalStart, finalEnd + 1); + } +} +``` Python: