|
| 1 | +// Manacher's algorithm is used to find the longest palindromic substring in any string. It is |
| 2 | +// required to solve sub-problems of some very hard problems. |
| 3 | +// Manacher's algorithm was invented by Manacher for listing all the palindromes that appear at |
| 4 | +// the start of any given string, it was later observed that the same algorithm can be used to |
| 5 | +// find the longest palindromic substring of any string in linear time. |
| 6 | + |
| 7 | +#include <iostream> |
| 8 | +#include <vector> |
| 9 | +#include <algorithm> |
| 10 | +using namespace std; |
| 11 | + |
| 12 | +// A function to print a substring. |
| 13 | +void printSubstring(string str, int left, int right){ |
| 14 | + for (int i = left; i <= right; i++) |
| 15 | + cout << str[i]; |
| 16 | +} |
| 17 | + |
| 18 | +// Implementation of Manacher's Algorithm |
| 19 | +void longestPalSubstring(string s){ |
| 20 | + /* |
| 21 | + If length of given string is n then its length after |
| 22 | + inserting n+1 "#", one "@", and one "$" will be |
| 23 | + (n) + (n+1) + (1) + (1) = 2n+3 |
| 24 | + */ |
| 25 | + int strLen = 2 * s.length() + 3; |
| 26 | + char* sChars = new char[strLen]; |
| 27 | + |
| 28 | + /* |
| 29 | + Inserting special characters to ignore special cases |
| 30 | + at the beginning and end of the array |
| 31 | + "abc" -> @ # a # b # c # $ |
| 32 | + "" -> @#$ |
| 33 | + "a" -> @ # a # $ |
| 34 | + */ |
| 35 | + sChars[0] = '@'; |
| 36 | + sChars[strLen - 1] = '$'; |
| 37 | + int t = 1; |
| 38 | + |
| 39 | + for (char c : s){ |
| 40 | + sChars[t++] = '#'; |
| 41 | + sChars[t++] = c; |
| 42 | + } |
| 43 | + sChars[t] = '#'; |
| 44 | + |
| 45 | + int maxLen = 0; |
| 46 | + int start = 0; |
| 47 | + int maxRight = 0; |
| 48 | + int center = 0; |
| 49 | + int* p = new int[strLen]; // i's radius, which doesn't include i |
| 50 | + |
| 51 | + for(int i = 1; i < strLen - 1; i++){ |
| 52 | + if (i < maxRight){ |
| 53 | + p[i] = min(maxRight - i, p[2 * center - i]); |
| 54 | + } |
| 55 | + |
| 56 | + // Expanding along the center |
| 57 | + while (sChars[i + p[i] + 1] == sChars[i - p[i] - 1]){ |
| 58 | + p[i]++; |
| 59 | + } |
| 60 | + |
| 61 | + // Updating center and its bound |
| 62 | + if (i + p[i] > maxRight){ |
| 63 | + center = i; |
| 64 | + maxRight = i + p[i]; |
| 65 | + } |
| 66 | + |
| 67 | + // Updating ans |
| 68 | + if (p[i] > maxLen){ |
| 69 | + start = (i - p[i] - 1) / 2; |
| 70 | + maxLen = p[i]; |
| 71 | + } |
| 72 | + } |
| 73 | + |
| 74 | + // Printing the longest palindromic substring |
| 75 | + cout << "The Longest Palindromic Substring is: "; |
| 76 | + printSubstring(s, start, start + maxLen - 1); |
| 77 | +} |
| 78 | + |
| 79 | +// Driver Code |
| 80 | +int main(){ |
| 81 | + string str = "daabddfddbegtd"; |
| 82 | + |
| 83 | + longestPalSubstring(str); |
| 84 | + return 0; |
| 85 | +} |
| 86 | + |
| 87 | +Time Complexity: O(N). |
| 88 | +Space Complexity: O(N). |
0 commit comments