214. Shortest Palindrome

2020-11-03  本文已影响0人  Ysgc

Given a string s, you can 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: s = "aacecaaa"
Output: "aaacecaaa"
Example 2:

Input: s = "abcd"
Output: "dcbabcd"

Constraints:

0 <= s.length <= 5 * 104
s consists of lowercase English letters only.

// brute force
class Solution {
public:
    string shortestPalindrome(string s) {
        string r(s.rbegin(), s.rend());
        int length = s.size();
        for (int i=0; i<length; ++i) {
            if (s.compare(0, length-i, r, i, length-i) == 0) {
                return r+s.substr(length-i, i);
            }
            // cout << i << endl;
        }
        return "";
    }
};

Runtime: 12 ms, faster than 28.67% of C++ online submissions for Shortest Palindrome.
Memory Usage: 7.4 MB, less than 9.70% of C++ online submissions for Shortest Palindrome.


https://www.geeksforgeeks.org/reverse-a-string-in-c-cpp-different-methods/

https://www.cnblogs.com/grandyang/p/4523624.html

https://www.youtube.com/watch?v=GTJr8OvyEVQ

https://www.cnblogs.com/grandyang/p/6992403.html

class Solution {
public:
    string shortestPalindrome(string s) {
        string r(s.rbegin(), s.rend());
        int length = s.size();
        vector<int> next = BuildNext(s, length);
        
        int i = 0, j = 0;
        while (i < length) {
            if (r[i] == s[j]) {
                //match
                ++i;
                ++j;
            }
            else if (j == 0) {
                ++i;
            }
            else {
                j = next[j];
            }
        }
        
        return r + s.substr(j, length-j);
    }
    
    vector<int> BuildNext(const string& s, const int& length) {
        vector<int> next(length, 0);
        int i = 1, j = 0;
        while (i < length-1) {
            if (s[i] == s[j]) {
                // match
                ++i;
                ++j;
                next[i] = j;
            }
            else if (j == 0) {
                ++i;
            }
            else {
                j = next[j];
            }
        }
     
        return next;
    }
};

Runtime: 4 ms, faster than 94.27% of C++ online submissions for Shortest Palindrome.
Memory Usage: 7.6 MB, less than 9.70% of C++ online submissions for Shortest Palindrome.

KMP 算法:

上一篇下一篇

猜你喜欢

热点阅读