algorithms
algorithms copied to clipboard
Implement Manacher's Algorithm and Unit Tests for Longest Palindromic Substring
PR Description:
This PR introduces the implementation of Manacher's Algorithm, an efficient algorithm to find the longest palindromic substring in linear time O(n). Additionally, the PR includes a set of comprehensive unit tests to verify the correctness and performance of the algorithm under different scenarios.
Manacher's Algorithm:
The algorithm is designed to find the longest palindromic substring by transforming the input string to handle both even-length and odd-length palindromes uniformly. It expands around potential center points and optimizes the search by leveraging symmetry (mirroring) properties of palindromes. The approach ensures a linear time complexity O(n), making it suitable for handling large strings efficiently.
Use Cases of Manacher's Algorithm:
In cryptography, palindromes might be used in certain algorithms. Identifying the longest palindromic substrings in a ciphered message could help analyze the underlying structure or potential weaknesses.
Unit Tests:
Unit tests have been added to cover a wide range of scenarios:
- Single-character strings: Ensures the algorithm works with the simplest input.
- Even-length and odd-length palindromes: Tests standard palindrome cases like
"abba"and"racecar". - Mixed palindromes: Accepts multiple valid longest palindromic substrings (e.g.,
"babad"can return either"aba"or"bab"). - Edge cases: Handles inputs like empty strings, no palindromes, and full-string palindromes.
- Special character handling: Verifies the algorithm can correctly identify palindromes when special characters (e.g.,
"a!b!a") are involved.
Test Case Adjustment:
- The test case for the input
"babad"was adjusted to handle multiple valid outputs. Both"aba"and"bab"are correct longest palindromes for this input, so the test now accepts either of them.