214 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

class Solution {
public:
    string shortestPalindrome(string s) {
        int n = s.size();
        int i = n;
        string rev_s = s;
        reverse(rev_s.begin(), rev_s.end());
        for ( i = n; i >= 0; i-- ) {
            if ( s.substr(0, i) == rev_s.substr(n-i, i) ) break;
        }
        return rev_s.substr(0, n-i) + s;
    }
};

Notes
The problem can be converted to "find the longest palindrome starting with s[0]".

results matching ""

    No results matching ""