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".

Solution TLE,Solution2 AC

 

//TLE
class Solution {
private:
    bool isPalindrome(string s) {
        int left = 0;
        int right = s.length() - 1;
        while (left < right) {
            if (s[left++] != s[right--])
                return false;
        }
        return true;
    }
public:
    string shortestPalindrome(string s) {
        int len = s.length();
        if (len <= 1)
            return s;

        int k = 0;
        for (int i = len; i > 0; i--) {
            if (isPalindrome(s.substr(0, i))) {
                k = i;
                break;
            }
        }
        string remain = s.substr(k, len - k);
        reverse(remain.begin(), remain.end());
        return remain + s;
    }
};
//AC
class Solution2{
public:
    string shortestPalindrome(string s){
        int len = s.size();
        if(len <=1) return s;

        string v = s;
        reverse(v.begin(),v.end());

        int i;
        for (i=len;i>0;i--){
            if( s.substr(0,i) == v.substr(len-i))
                break;
        }
        return v.substr(0,len-i) + s;
    }
};

 

posted @ 2016-09-13 10:41  wxquare  阅读(218)  评论(0编辑  收藏  举报