Skip to content

Commit 678ed88

Browse files
solves longest palindromic substring
1 parent e866332 commit 678ed88

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

src/LongestPalindromicSubstring.java

+35
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
// https://leetcode.com/problems/longest-palindromic-substring
2+
3+
public class LongestPalindromicSubstring {
4+
public static void main(String[] args) {
5+
System.out.println(isPalindrome("caba", 1, 4));
6+
}
7+
8+
public static String longestPalindrome(String s) {
9+
final String s2 = new StringBuilder(s).reverse().toString();
10+
final int rows = s.length() + 1, columns = s2.length() + 1;
11+
final int[][] dp = new int[2][columns];
12+
int maxLength = 0, startIndex = -1;
13+
14+
for (int row = 1, i = 1 ; row < rows ; row++, i ^= 1) {
15+
for (int column = 1 ; column < columns ; column++) {
16+
dp[i][column] = s.charAt(row - 1) == s2.charAt(column - 1) ? dp[i ^ 1][column - 1] + 1 : 0;
17+
if (dp[i][column] > maxLength && isPalindrome(s, row - dp[i][column], row)) {
18+
maxLength = dp[i][column];
19+
startIndex = row - maxLength;
20+
}
21+
}
22+
}
23+
24+
return s.substring(startIndex, startIndex + maxLength);
25+
}
26+
27+
private static boolean isPalindrome(String s, int start, int end) {
28+
for (int i = start ; i < start + (end - start) / 2 ; i++) {
29+
if (s.charAt(i) != s.charAt(end - i - 1 + start)) {
30+
return false;
31+
}
32+
}
33+
return true;
34+
}
35+
}

0 commit comments

Comments
 (0)