-
Notifications
You must be signed in to change notification settings - Fork 821
/
Copy pathLongestPaliandromicSubstring.java
62 lines (57 loc) · 1.43 KB
/
LongestPaliandromicSubstring.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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
/* (C) 2024 YourCompanyName */
package dynamic_programming;
/**
* Created by gouthamvidyapradhan on 24/02/2017. Given a string s, find the longest palindromic
* substring in s. You may assume that the maximum length of s is 1000.
*
* <p>Example:
*
* <p>Input: "babad"
*
* <p>Output: "bab"
*
* <p>Note: "aba" is also a valid answer. Example:
*
* <p>Input: "cbbd"
*
* <p>Output: "bb"
*/
public class LongestPaliandromicSubstring {
/**
* Main method
*
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
System.out.println(new LongestPaliandromicSubstring().longestPalindrome("forgeeksskeegfor"));
}
public String longestPalindrome(String s) {
int l = s.length();
int startIndex = 0;
int maxLen = 1;
boolean[][] A = new boolean[l][l];
for (int i = 0, j = 0; i < l; i++, j++) A[i][j] = true;
for (int i = 0, j = i + 1; j < l; i++, j++) {
if (s.charAt(i) == s.charAt(j)) {
A[i][j] = true;
startIndex = i;
maxLen = 2;
}
}
for (int k = 3; k <= l; k++) {
for (int i = 0, j = k - 1; j < l; i++, j++) {
if (s.charAt(i) == s.charAt(j)) {
A[i][j] = A[i + 1][j - 1];
if (A[i][j]) {
if (k > maxLen) {
startIndex = i;
maxLen = k;
}
}
}
}
}
return s.substring(startIndex, startIndex + maxLen);
}
}