-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathlongest_palindrome.java
More file actions
71 lines (51 loc) · 1.71 KB
/
Copy pathlongest_palindrome.java
File metadata and controls
71 lines (51 loc) · 1.71 KB
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
63
64
65
66
67
68
69
70
/**
Given a string S, find the longest palindromic substring in S.
Substring of string S:
S[i...j] where 0 <= i <= j < len(S)
Palindrome string:
A string which reads the same backwards. More formally, S is palindrome if reverse(S) = S.
Incase of conflict, return the substring which occurs first ( with the least starting index ).
Example :
Input : "aaaabaaa"
Output : "aaabaaa"
*/
package interview.interview.java.strings;
public class longest_palindrome {
public static void main(String[] args) {
String input = "aaaabaaa";
String exp_output = "aaabaaa";
String result = longestPalindrome(input);
assert result.equals(exp_output);
System.out.println("Success!");
}
public static String longestPalindrome(String str) {
int n = str.length();
boolean[][] dp = new boolean[n][n];
//Arrays.fill(dp, false);
int longestBegin = 0;
int maxLen = 1;
for(int i = 0; i < n; i++) {
dp[i][i] = true;
}
for(int i = 1; i < n; i++) {
if(str.charAt(i) == str.charAt(i-1)) {
dp[i-1][i] = true;
longestBegin = i - 1;
maxLen = 2;
}
}
for(int len = 3; len <= n; len++) {
for(int i = 0; i < n - len + 1; i++) {
int j = i + len - 1;
if(str.charAt(i) == str.charAt(j) && dp[i+1][j-1]) {
dp[i][j] = true;
if (len > maxLen) {
maxLen = len;
longestBegin = i;
}
}
}
}
return str.substring(longestBegin, longestBegin + maxLen);
}
}