您的位置:首页 > 其它

Leetcode -- Shortest Palindrome

2015-10-28 22:05 288 查看
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;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: