Uh oh!
There was an error while loading. Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork 21.3k
Expand file tree
/
Copy pathLongestPalindromicSubstring.java
More file actions
Latest commit
39 lines (36 loc) · 1.27 KB
/
Copy pathLongestPalindromicSubstring.java
File metadata and controls
39 lines (36 loc) · 1.27 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
packagecom.thealgorithms.dynamicprogramming;
/**
* Class for finding the longest palindromic substring within a given string.
* <p>
* A palindromic substring is a sequence of characters that reads the same backward as forward.
* This class uses a dynamic programming approach to efficiently find the longest palindromic substring.
*
*/
publicfinalclassLongestPalindromicSubstring {
privateLongestPalindromicSubstring() {
}
publicstaticStringlps(Stringinput) {
if (input == null || input.isEmpty()) {
returninput;
}
boolean[][] arr = newboolean[input.length()][input.length()];
intstart = 0;
intend = 0;
for (intg = 0; g < input.length(); g++) {
for (inti = 0, j = g; j < input.length(); i++, j++) {
if (g == 0) {
arr[i][j] = true;
} elseif (g == 1) {
arr[i][j] = input.charAt(i) == input.charAt(j);
} else {
arr[i][j] = input.charAt(i) == input.charAt(j) && arr[i + 1][j - 1];
}
if (arr[i][j]) {
start = i;
end = j;
}
}
}
returninput.substring(start, end + 1);
}
}