-
Notifications
You must be signed in to change notification settings - Fork 20k
Add Manacher’s Algorithm for Longest Palindromic Substring #5462
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 4 commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
09661a2
Added Manacher Algorithm
donutt03 b4ae4aa
Formatted ManacherTest.java
donutt03 4c11045
Formatted Manacher.java
donutt03 f7f498c
Merge branch 'master' into manachers-algorithm
donutz03 c1eca26
Refactor: Update Manacher's algorithm tests and improve readability
donutt03 f5a2e36
Merge remote-tracking branch 'origin/manachers-algorithm' into manach…
donutt03 d8dabd8
Merge branch 'master' into manachers-algorithm
donutz03 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,91 @@ | ||
package com.thealgorithms.strings; | ||
|
||
/** | ||
* Uncyclopedia: https://en.wikipedia.org/wiki/Longest_palindromic_substring#Manacher's_algorithm | ||
*/ | ||
public final class Manacher { | ||
|
||
// Private constructor to prevent instantiation | ||
private Manacher() { | ||
} | ||
|
||
/** | ||
* Test code for Manacher's Algorithm | ||
*/ | ||
public static void main(String[] args) { | ||
donutz03 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
assert longestPalindrome("babad").equals("bab") || longestPalindrome("babad").equals("aba"); | ||
assert longestPalindrome("cbbd").equals("bb"); | ||
assert longestPalindrome("a").equals("a"); | ||
assert longestPalindrome("ac").equals("a") || longestPalindrome("ac").equals("c"); | ||
} | ||
|
||
/** | ||
* Finds the longest palindromic substring using Manacher's Algorithm | ||
* | ||
* @param s The input string | ||
* @return The longest palindromic substring in {@code s} | ||
*/ | ||
public static String longestPalindrome(String s) { | ||
alxkm marked this conversation as resolved.
Show resolved
Hide resolved
|
||
// Preprocess the string to avoid even-length palindrome issues | ||
String processedString = preprocess(s); | ||
donutz03 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
int n = processedString.length(); | ||
donutz03 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
int[] p = new int[n]; // Array to store the radius of palindromes | ||
donutz03 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
// Separate variable declarations into individual statements | ||
donutz03 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
int center = 0; | ||
int rightBoundary = 0; | ||
int maxLen = 0; | ||
int centerIndex = 0; | ||
|
||
// Iterate over the preprocessed string to calculate the palindrome radii | ||
donutz03 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
for (int i = 1; i < n - 1; i++) { | ||
// Mirror the current index i to find its corresponding mirrored index | ||
int mirror = 2 * center - i; | ||
|
||
// If the current index is within the right boundary, mirror the palindrome radius | ||
if (i < rightBoundary) { | ||
p[i] = Math.min(rightBoundary - i, p[mirror]); | ||
} | ||
|
||
// Try to expand the palindrome centered at i | ||
while (processedString.charAt(i + 1 + p[i]) == processedString.charAt(i - 1 - p[i])) { | ||
p[i]++; | ||
} | ||
|
||
// Update center and right boundary if palindrome expands beyond current right boundary | ||
if (i + p[i] > rightBoundary) { | ||
center = i; | ||
rightBoundary = i + p[i]; | ||
} | ||
|
||
// Track the maximum length and center index of the longest palindrome found so far | ||
if (p[i] > maxLen) { | ||
maxLen = p[i]; | ||
centerIndex = i; | ||
} | ||
} | ||
|
||
// Extract the longest palindrome from the original string | ||
donutz03 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
int start = (centerIndex - maxLen) / 2; // Get the starting index in the original string | ||
donutz03 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
return s.substring(start, start + maxLen); | ||
} | ||
|
||
/** | ||
* Preprocesses the input string by inserting a special character ('#') between each character | ||
* and adding '^' at the start and '$' at the end to avoid boundary conditions. | ||
* | ||
* @param s The original string | ||
* @return The preprocessed string with additional characters | ||
*/ | ||
private static String preprocess(String s) { | ||
if (s.isEmpty()) { | ||
return "^$"; | ||
} | ||
StringBuilder sb = new StringBuilder("^"); | ||
for (char c : s.toCharArray()) { | ||
sb.append('#').append(c); | ||
} | ||
sb.append("#$"); | ||
return sb.toString(); | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,37 @@ | ||
package com.thealgorithms.strings; | ||
|
||
import static org.junit.jupiter.api.Assertions.assertEquals; | ||
|
||
import org.junit.jupiter.api.Test; | ||
|
||
public class ManacherTest { | ||
donutz03 marked this conversation as resolved.
Show resolved
Hide resolved
alxkm marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
@Test | ||
public void testLongestPalindrome() { | ||
assertEquals("aabcdefggfedcbaa", Manacher.longestPalindrome("abracadabraabcdefggfedcbaabracadabra")); // Long string with embedded palindrome | ||
assertEquals("racecar", Manacher.longestPalindrome("somelongtextwithracecarmiddletext")); // Longer string with racecar palindrome | ||
assertEquals("ananananananana", Manacher.longestPalindrome("bananananananana")); // Repetitive pattern with palindrome | ||
assertEquals("defgfed", Manacher.longestPalindrome("qwertydefgfedzxcvbnm")); // Palindrome in middle of long string | ||
assertEquals("abcdefghijklmnopqrstuvwxyzzyxwvutsrqponmlkjihgfedcba", Manacher.longestPalindrome("abcdefghijklmnopqrstuvwxyzzyxwvutsrqponmlkjihgfedcba")); // Symmetrical section | ||
} | ||
|
||
@Test | ||
public void testEmptyAndSingle() { | ||
assertEquals("", Manacher.longestPalindrome("")); // Empty string | ||
assertEquals("a", Manacher.longestPalindrome("a")); // Single character | ||
} | ||
|
||
@Test | ||
public void testComplexCases() { | ||
assertEquals("tattarrattat", Manacher.longestPalindrome("abcdefghijklmnopqrstuvwxyzttattarrattatabcdefghijklmnopqrstuvwxyz")); // Long palindrome inside a large string | ||
assertEquals("aaaaabaaaaa", Manacher.longestPalindrome("aaaaabaaaaacbaaaaa")); // Large repetitive character set | ||
assertEquals("abcdefghhgfedcba", Manacher.longestPalindrome("sometextrandomabcdefgabcdefghhgfedcbahijklmnopqrstuvwxyz")); // Large string with clear palindromic section | ||
assertEquals("madaminedenimadam", Manacher.longestPalindrome("therewasasignthatsaidmadaminedenimadamitwasthereallalong")); // Famous palindrome within a long string | ||
} | ||
|
||
@Test | ||
public void testSentencePalindromes() { | ||
assertEquals("lanacanal", Manacher.longestPalindrome("XThisisalongtextbuthiddeninsideisAmanaplanacanalPanamaWhichweknowisfamous")); | ||
assertEquals("everoddoreve", Manacher.longestPalindrome("AverylongstringthatcontainsNeveroddoreveninahiddenmanner")); // Another sentence-like palindrome | ||
} | ||
} |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.