-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathLongestPalindromicSubstring.java
41 lines (35 loc) · 1.41 KB
/
LongestPalindromicSubstring.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
/*
Given a string S, find the longest palindromic substring in S.
Assumptions
There exists one unique longest palindromic substring.
The input S is not null.
Examples
Input: "abbc"
Output: "bb"
Input: "abcbcbd"
Output: "bcbcb"
*/
public class LongestPalindromicSubstring {
public String longestPalindrome(String s) {
int l = 0, r = 0, n = s.length();
if (n == 0) return "";
boolean[][] dp = new boolean[n][n]; // [i, j] in string is palindrome
for (int j = 0; j < n; j++)
for (int i = 0; i <= j; i++) // fix position of j first, then check all substring [i, j]
if (s.charAt(i) == s.charAt(j) && (i + 1 >= j || dp[i+1][j-1])) {
dp[i][j] = true;
if (j - i > r - l) { // longer Palindromic Substring found
r = j;
l = i;
}
}
return s.substring(l, r + 1);
}
public static void main(String[] args) {
LongestPalindromicSubstring lps = new LongestPalindromicSubstring();
System.out.println(lps.longestPalindrome("abcbcbd").equals("bcbcb"));
System.out.println(lps.longestPalindrome("bcbccaacdca").equals("acdca"));
System.out.println(lps.longestPalindrome("dbdcbdbabbacd").equals("abba"));
System.out.println(lps.longestPalindrome("").equals(""));
}
}