Shortest Palindrome

Given a string S, you are allowed to convert it to a palindrome by adding characters in front of it. Find and return the shortest palindrome you can find by performing this transformation.

For example:

Given "aacecaaa", return "aaacecaaa".

Given "abcd", return "dcbabcd".

Analyse: It asks us to get the longest palindrome starting from index 0. Suppose the longest palindrome is s_1, and the original string is s, remaining part is s_2 = s - s_1, then the result should be Reverse(s_2) + s.

For example, if the string is aaabbbccc, s_1 should be aa, s_2 is abbbccc, the result should be cccbbba|aaabbbccc

string     aaabbbccc

s_1       aa

s_2     abbbccc

result     cccbbba|aaabbbccc

 

Start from the back, check if s[0] == s[i] and if s[0...i] is palindrome. If so, compute the result.

Time limit exceeded. 

 1 class Solution {
 2 public:
 3     string shortestPalindrome(string s) {
 4         if (s.size() < 2) return s;
 5         // find the longest palindrome substring starting from s[0]
 6         int end = 0;
 7         for (int i = s.size() - 1; i >= 0; i--) {
 8             if (s[i] == s[0] && isPalindrome(s, 0, i)) {
 9                 end = i;
10                 break;
11             }
12         }
13         
14         // insert [end + 1, s.size() - 1] in front of s in reverse order
15         string result;
16         for (int i = s.size() - 1; i > end; i--) 
17             result += s[i];
18         result += s;
19         return result;
20     }
21 private:
22     bool isPalindrome(string s, int start, int end) {
23         while (start < end) {
24             if (s[start++] != s[end--]) return false;
25         }
26         return true;
27     }
28 };
View Code
原文地址:https://www.cnblogs.com/amazingzoe/p/5887354.html