Skip to content

Commit f8ba038

Browse files
Sean PrashadSean Prashad
authored andcommitted
Add 5_Longest_Palindromic_Substring.java
1 parent f09e746 commit f8ba038

File tree

1 file changed

+23
-0
lines changed

1 file changed

+23
-0
lines changed
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
class Solution {
2+
public String longestPalindrome(String s) {
3+
if (s == null || s.length() == 0) {
4+
return s;
5+
}
6+
7+
int start = 0, end = 0, n = s.length();
8+
boolean[][] dp = new boolean[n][n];
9+
10+
for (int i = n - 1; i >= 0; i--) {
11+
for (int j = i; j < n; j++) {
12+
dp[i][j] = s.charAt(i) == s.charAt(j) && (j - i < 2 || dp[i + 1][j - 1]);
13+
14+
if (dp[i][j] && j - i > end - start) {
15+
start = i;
16+
end = j;
17+
}
18+
}
19+
}
20+
21+
return s.substring(start, end + 1);
22+
}
23+
}

0 commit comments

Comments
 (0)