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"
.
分析:
只需要找到以第一个字符为起始点的最长回文子序列即可。
class Solution {
public:
string shortestPalindrome(string s) {
int n=s.size();
if(n==0) return s;
int i;
string t=s;
reverse(t.begin(),t.end());
for(i=0;i<n;++i)
if(s.substr(0,n-i)==t.substr(i))
break;
return t.substr(0,i)+s;
}
};