Skip to content

Commit e84f885

Browse files
committed
Updated Longest Palindromic Substring.java
1 parent c9e1516 commit e84f885

File tree

1 file changed

+25
-21
lines changed

1 file changed

+25
-21
lines changed
+25-21
Original file line numberDiff line numberDiff line change
@@ -1,24 +1,28 @@
11
class Solution {
2-
public String longestPalindrome(String s) {
3-
int start = 0;
4-
int end = 0;
5-
for (int i = 0; i < s.length(); i++) {
6-
int lenOne = helper(s, i, i);
7-
int lenTwo = helper(s, i, i + 1);
8-
int maxLength = Math.max(lenOne, lenTwo);
9-
if (maxLength > end - start) {
10-
start = i - (maxLength - 1) / 2;
11-
end = i + maxLength / 2;
12-
}
2+
public String longestPalindrome(String s) {
3+
int n = s.length();
4+
boolean[][] dp = new boolean[n][n];
5+
int[] result = new int[]{0, 0};
6+
for (int i = 0; i < n; i++) {
7+
dp[i][i] = true;
8+
}
9+
for (int i = 0; i < n - 1; i++) {
10+
if (s.charAt(i) == s.charAt(i + 1)) {
11+
dp[i][i + 1] = true;
12+
result[0] = i;
13+
result[1] = i + 1;
14+
}
15+
}
16+
for (int i = 2; i < n; i++) {
17+
for (int j = 0; j < n - i; j++) {
18+
int k = i + j;
19+
if (s.charAt(j) == s.charAt(k) && dp[j + 1][k - 1]) {
20+
dp[j][k] = true;
21+
result[0] = j;
22+
result[1] = k;
23+
}
24+
}
25+
}
26+
return s.substring(result[0], result[1] + 1);
1327
}
14-
return s.substring(start, end + 1);
15-
}
16-
17-
private int helper(String s, int left, int right) {
18-
while (left >= 0 && right < s.length() && s.charAt(left) == s.charAt(right)) {
19-
left--;
20-
right++;
21-
}
22-
return right - left - 1;
23-
}
2428
}

0 commit comments

Comments
 (0)