214. 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"
.
刚开始写的代码运行超时。
如下:
1 string shortestPalindrome(string s) { 2 3 int end = 0; 4 for (int i = 1; i < s.length(); ++i) 5 { 6 int j = 0, k = i; 7 if (end==k+1 && ) 8 while (s[j] == s[k]) 9 { 10 if (k - j>1) 11 { 12 ++j; 13 --k; 14 } 15 else 16 { 17 end = i; 18 break; 19 } 20 } 21 } 22 string str = s; 23 for (int i = end + 1; i < s.length(); ++i) 24 { 25 str.insert(0, 1, s[i]); 26 } 27 return str; 28 }
后来又参考别人的KPM算法的,
1 string shortestPalindrome(string s) { 2 string rev_s = s; 3 reverse(rev_s.begin(), rev_s.end()); 4 string l = s + "#" + rev_s; 5 6 vector<int> p(l.size(), 0); 7 for (int i = 1; i < l.size(); i++) { 8 int j = p[i - 1]; 9 while (j > 0 && l[i] != l[j]) 10 j = p[j - 1]; 11 p[i] = (j += l[i] == l[j]); 12 } 13 14 return rev_s.substr(0, s.size() - p[l.size() - 1]) + s; 15 }