Shortest palindrome string (KMP)

Title
Given a string s, you can convert it to a palindrome by adding characters in front of the string. Find and return the shortest palindrome string that can be converted in this way.
Idea: The key is to find the longest palindrome prefix string of string s, you can construct its reverse string rev, long string s 2 = s + # + r e v s2 = s+\#+rev , find the nxt value of the last position of s2, that is, the length of the longest palindrome prefix string of the corresponding string s.

class Solution {
public:
    //KMP寻找最长前缀回文串
    string shortestPalindrome(string s) {
        int n = s.size();
        string rev = s;
        reverse(rev.begin(),rev.end());
        string s2 = s + "#" +rev;
        int n2 = s2.size();
        vector<int> nxt(n2+1,-1);
        int i = 0,j = -1;
        nxt[0] = -1;
        while(i < n2) {
            if(j == -1 || s2[j] == s2[i]) {
                ++i;++j;
                nxt[i] = j;
            }
            else j = nxt[j];
        }
        return rev.substr(0,n-nxt[n2])+s;
    }
};
Published 152 original articles · won praise 2 · Views 6440

Guess you like

Origin blog.csdn.net/weixin_43918473/article/details/105452343