-
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 all 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,69 @@ | ||
package com.thealgorithms.strings; | ||
|
||
/** | ||
* Uncyclopedia: https://en.wikipedia.org/wiki/Longest_palindromic_substring#Manacher's_algorithm | ||
*/ | ||
public final class Manacher { | ||
|
||
private Manacher() { | ||
} | ||
|
||
/** | ||
* 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) { | ||
final String processedString = preprocess(s); | ||
int[] palindromeLengths = new int[processedString.length()]; | ||
int center = 0; | ||
int rightBoundary = 0; | ||
int maxLen = 0; | ||
int centerIndex = 0; | ||
|
||
for (int i = 1; i < processedString.length() - 1; i++) { | ||
int mirror = 2 * center - i; | ||
|
||
if (i < rightBoundary) { | ||
palindromeLengths[i] = Math.min(rightBoundary - i, palindromeLengths[mirror]); | ||
} | ||
|
||
while (processedString.charAt(i + 1 + palindromeLengths[i]) == processedString.charAt(i - 1 - palindromeLengths[i])) { | ||
palindromeLengths[i]++; | ||
} | ||
|
||
if (i + palindromeLengths[i] > rightBoundary) { | ||
center = i; | ||
rightBoundary = i + palindromeLengths[i]; | ||
} | ||
|
||
if (palindromeLengths[i] > maxLen) { | ||
maxLen = palindromeLengths[i]; | ||
centerIndex = i; | ||
} | ||
} | ||
|
||
final int start = (centerIndex - maxLen) / 2; | ||
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,53 @@ | ||
package com.thealgorithms.strings; | ||
|
||
import static org.junit.jupiter.api.Assertions.assertEquals; | ||
|
||
import java.util.stream.Stream; | ||
import org.junit.jupiter.params.ParameterizedTest; | ||
import org.junit.jupiter.params.provider.Arguments; | ||
import org.junit.jupiter.params.provider.MethodSource; | ||
|
||
public class ManacherTest { | ||
donutz03 marked this conversation as resolved.
Show resolved
Hide resolved
alxkm marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
@ParameterizedTest | ||
@MethodSource("provideTestCasesForLongestPalindrome") | ||
public void testLongestPalindrome(String input, String expected) { | ||
assertEquals(expected, Manacher.longestPalindrome(input)); | ||
} | ||
|
||
private static Stream<Arguments> provideTestCasesForLongestPalindrome() { | ||
return Stream.of(Arguments.of("abracadabraabcdefggfedcbaabracadabra", "aabcdefggfedcbaa"), Arguments.of("somelongtextwithracecarmiddletext", "racecar"), Arguments.of("bananananananana", "ananananananana"), Arguments.of("qwertydefgfedzxcvbnm", "defgfed"), | ||
Arguments.of("abcdefghijklmnopqrstuvwxyzzyxwvutsrqponmlkjihgfedcba", "abcdefghijklmnopqrstuvwxyzzyxwvutsrqponmlkjihgfedcba")); | ||
} | ||
|
||
@ParameterizedTest | ||
@MethodSource("provideTestCasesForEmptyAndSingle") | ||
public void testEmptyAndSingle(String input, String expected) { | ||
assertEquals(expected, Manacher.longestPalindrome(input)); | ||
} | ||
|
||
private static Stream<Arguments> provideTestCasesForEmptyAndSingle() { | ||
return Stream.of(Arguments.of("", ""), Arguments.of("a", "a")); | ||
} | ||
|
||
@ParameterizedTest | ||
@MethodSource("provideTestCasesForComplexCases") | ||
public void testComplexCases(String input, String expected) { | ||
assertEquals(expected, Manacher.longestPalindrome(input)); | ||
} | ||
|
||
private static Stream<Arguments> provideTestCasesForComplexCases() { | ||
return Stream.of(Arguments.of("abcdefghijklmnopqrstuvwxyzttattarrattatabcdefghijklmnopqrstuvwxyz", "tattarrattat"), Arguments.of("aaaaabaaaaacbaaaaa", "aaaaabaaaaa"), Arguments.of("sometextrandomabcdefgabcdefghhgfedcbahijklmnopqrstuvwxyz", "abcdefghhgfedcba"), | ||
Arguments.of("therewasasignthatsaidmadaminedenimadamitwasthereallalong", "madaminedenimadam")); | ||
} | ||
|
||
@ParameterizedTest | ||
@MethodSource("provideTestCasesForSentencePalindromes") | ||
public void testSentencePalindromes(String input, String expected) { | ||
assertEquals(expected, Manacher.longestPalindrome(input)); | ||
} | ||
|
||
private static Stream<Arguments> provideTestCasesForSentencePalindromes() { | ||
return Stream.of(Arguments.of("XThisisalongtextbuthiddeninsideisAmanaplanacanalPanamaWhichweknowisfamous", "lanacanal"), Arguments.of("AverylongstringthatcontainsNeveroddoreveninahiddenmanner", "everoddoreve")); | ||
} | ||
} |
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.