Skip to content

Commit 816a061

Browse files
Update Manacher.java
1 parent 98cb53d commit 816a061

File tree

1 file changed

+24
-13
lines changed

1 file changed

+24
-13
lines changed
Lines changed: 24 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,30 +1,44 @@
11
public class ManacherAlgorithm {
2+
3+
// Preprocesses the input string by adding boundary characters
24
private String preprocess(String s) {
35
StringBuilder sb = new StringBuilder();
4-
sb.append('^');
6+
sb.append('^'); // Add starting boundary
57
for (int i = 0; i < s.length(); i++) {
6-
sb.append('#');
8+
sb.append('#'); // Add boundary between characters
79
sb.append(s.charAt(i));
810
}
9-
sb.append("#$");
11+
sb.append("#$"); // Add ending boundary
1012
return sb.toString();
1113
}
14+
15+
// Manacher's Algorithm to find the longest palindromic substring
1216
public String longestPalindrome(String s) {
1317
String T = preprocess(s);
1418
int n = T.length();
15-
int[] P = new int[n];
16-
int C = 0, R = 0;
19+
int[] P = new int[n]; // Array to store the lengths of palindromes
20+
int C = 0, R = 0; // C is the center, R is the right boundary
21+
22+
// Iterate through the transformed string
1723
for (int i = 1; i < n - 1; i++) {
18-
int mirror = 2 * C - i;
24+
int mirror = 2 * C - i; // Mirror of i with respect to the center C
25+
26+
// Use previously computed values or set P[i] to 0
1927
P[i] = (R > i) ? Math.min(R - i, P[mirror]) : 0;
28+
29+
// Expand around i
2030
while (T.charAt(i + 1 + P[i]) == T.charAt(i - 1 - P[i])) {
2131
P[i]++;
22-
}
32+
}
33+
34+
// Update center and right boundary if the palindrome expands beyond R
2335
if (i + P[i] > R) {
2436
C = i;
2537
R = i + P[i];
2638
}
2739
}
40+
41+
// Find the longest palindrome in P
2842
int maxLen = 0;
2943
int centerIndex = 0;
3044
for (int i = 1; i < n - 1; i++) {
@@ -33,13 +47,10 @@ public String longestPalindrome(String s) {
3347
centerIndex = i;
3448
}
3549
}
50+
51+
// Calculate the starting index of the longest palindromic substring
3652
int start = (centerIndex - maxLen) / 2;
3753
return s.substring(start, start + maxLen);
3854
}
39-
40-
public static void main(String[] args) {
41-
ManacherAlgorithm ma = new ManacherAlgorithm();
42-
String input = "babad";
43-
System.out.println("Longest Palindromic Substring: " + ma.longestPalindrome(input));
44-
}
4555
}
56+

0 commit comments

Comments
 (0)