Skip to content

Commit 20a7ada

Browse files
committed
add: LongestPalindromeInAString
1 parent 5249572 commit 20a7ada

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
public class LongestPalindromeInAString {
2+
public String longestPalindromeInAString(String s) {
3+
int n = s.length();
4+
if (n == 0) {
5+
return "";
6+
}
7+
boolean[][] dp = new boolean[n][n];
8+
int maxLen = 1;
9+
int startIndex = 0;
10+
// Base case: a single character is always a palindrome.
11+
for (int i = 0; i < n; i++) {
12+
dp[i][i] = true;
13+
}
14+
// Base case: a substring of length two is a palindrome if both
15+
// characters are the same.
16+
for (int i = 0; i < n - 1; i++) {
17+
if (s.charAt(i) == s.charAt(i + 1)) {
18+
dp[i][i + 1] = true;
19+
maxLen = 2;
20+
startIndex = i;
21+
}
22+
}
23+
// Find palindromic substrings of length 3 or greater.
24+
for (int substringLen = 3; substringLen < n + 1; substringLen++) {
25+
// Iterate through each substring of length 'substringLen'.
26+
for (int i = 0; i < n - substringLen + 1; i++) {
27+
int j = i + substringLen - 1;
28+
// If the first and last characters are the same, and the
29+
// inner substring is a palindrome, then the current
30+
// substring is a palindrome.
31+
if (s.charAt(i) == s.charAt(j) && dp[i + 1][j - 1]) {
32+
dp[i][j] = true;
33+
maxLen = substringLen;
34+
startIndex = i;
35+
}
36+
}
37+
}
38+
return s.substring(startIndex, startIndex + maxLen);
39+
}
40+
}

0 commit comments

Comments
 (0)