Skip to content

Commit

Permalink
Merge pull request youngyangyang04#2144 from Lozakaka/patch-31
Browse files Browse the repository at this point in the history
新增java解法 for leetcode 5.
  • Loading branch information
youngyangyang04 authored Jul 11, 2023
2 parents 88cba5e + 346e927 commit 85f7291
Showing 1 changed file with 31 additions and 0 deletions.
31 changes: 31 additions & 0 deletions problems/0647.回文子串.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:

Expand Down

0 comments on commit 85f7291

Please sign in to comment.