From 346e927f6c8a98594b444233dede3bca8f6ad5eb Mon Sep 17 00:00:00 2001 From: Terry Liu <102352821+Lozakaka@users.noreply.github.com> Date: Tue, 20 Jun 2023 17:51:21 -0400 Subject: [PATCH] =?UTF-8?q?=E6=96=B0=E5=A2=9Ejava=E8=A7=A3=E6=B3=95=20for?= =?UTF-8?q?=20leetcode=205.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 新增java解法 for leetcode 5. 感覺卡哥可以提一下,其實在下一偏有提到,但是真的有關聯的這一篇沒有提到:這一題稍微改一下就能通過兩題,這一點我沒有寫在這個fork上。 --- problems/0647.回文子串.md | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) 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: