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.
Example 1:
Input: "aacecaaa"
Output: "aaacecaaa"
Example 2:
Input: "abcd"
Output: "dcbabcd"
- 方法一:暴力搜索
class Solution {
public:
bool Check(string s,int low,int high)
{
if(low==high)
return true;
while(low<high)
{
if(s[low]!=s[high])
return false;
low++;
high--;
}
return true;
}
string shortestPalindrome(string s)
{
int i,j;
int len;
string result="";
len=s.length();
if(len<=1)
return s;
for(;len>0;len--)
{
if(s[0]==s[len]&&Check(s,0,len))
break;
}
//找到后比如 0-len表示最长的回文,len-length()-1就是没有匹配上的,反转加在最前面就是
for(i=s.length()-1;i>len;i--)
result+=s[i];
result+=s;
return result;
}
};
- 方法二:首先翻转字符串,然后比较原字符串s的前缀与翻转字符串t的对应位置的后缀是否相等,起始位置是比较s和t是否相等,如果相等,说明s本身就是回文串,不用添加任何字符,直接返回即可;如果不想等,s去掉最后一位,t去掉第一位,继续比较,以此类推直至有相等,或者循环结束,这样我们就能将两个字符串在正确的位置拼接起来了。
class Solution {
public:
string shortestPalindrome(string s) {
string t = s;
reverse(t.begin(), t.end());
int n = s.size(), i = 0;
for (i = n; i >= 0; --i) {
if (s.substr(0, i) == t.substr(n - i,i)) {
break;
}
}
return t.substr(0, n - i) + s;
}
};