Merge pull request #2144 from Lozakaka/patch-31

新增java解法 for leetcode 5.
This commit is contained in:
程序员Carl
2023-07-11 11:26:53 +08:00
committed by GitHub

View File

@ -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 Python