Leetcode 214. Shortest Palindrome
214. Shortest Palindrome
Total Accepted: 21546
Total Submissions: 105732
Difficulty: Hard
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"
.
思路:
主要是KMP算法中的前缀字符串和后缀字符串的匹配问题,利用KMP算法的“部分匹配表”。先将原字符串s反转为rev_s,然后产生新的字符串l=rev_s+“#”+s。求出包含l最后一个字符的最长后缀长度,然后求出s的补齐回文字符串。
代码:
1 class Solution { 2 public: 3 string shortestPalindrome(string s) { 4 string rev_s=s; 5 reverse(rev_s.begin(),rev_s.end()); 6 string l=s+"#"+rev_s; 7 int i,j; 8 vector<int> v(l.size(),0); 9 for(i=1;i<l.size();i++){ 10 j=v[i-1]; 11 while(j>0&&l[j]!=l[i]) j=v[j-1]; 12 v[i]=j+(l[j]==l[i]); 13 } 14 return rev_s.substr(0,s.size()-v[l.size()-1])+s; 15 } 16 };