[LeetCode] Shortest Palindrome

The basic idea is as follows: find the longest palindromic string that contains the first character of s. Then get the substring after this longest palindrome substring, reverse it and add it to the head of s.

You need to implement the Manacher's algorithm for this problem. You may want to refer to this nice article on Manacher's algorithm.

The code is as follows.

 1     string process(string s) {
 2         int n = s.length();
 3         string t(2 * n + 3, '#');
 4         t[0] = '$';
 5         t[2 * n + 2] = '%';
 6         for (int i = 0; i < n; i++)
 7             t[2 * (i + 1)] = s[i];
 8         return t;
 9     }
10     string shortestPalindrome(string s) {
11         if (s.length() <= 1) return s;
12         string t = process(s);
13         int n = t.length();
14         int* plen = new int[n];
15         int center = 0, right = 0;
16         for (int i = 1; i < n - 1; i++) {
17             int i_mirror = 2 * center - i;
18             plen[i] = (right > i) ? min(plen[i_mirror], right - i) : 0;
19             while (t[i + plen[i] + 1] == t[i - plen[i] - 1])
20                 plen[i]++;
21             if (i + plen[i] > right) {
22                 center = i;
23                 right = i + plen[i];
24             }
25         }
26         int pos;
27         for (int i = 1; i < n - 1; i++)
28             if (i - plen[i] == 1)
29                 pos = plen[i];
30         string tail = s.substr(pos);
31         reverse(tail.begin(), tail.end());
32         return tail + s;
33     }

你可能感兴趣的:(LeetCode)