leetcode 214: Shortest Palindrome

来源:互联网 发布:尘埃3知乎 编辑:程序博客网 时间:2024/05/16 06:08

Use KMP algorithm. First, get the reverse of the string s called new_s, and add s, a special character ('#') and new_s together. Word out the next array on this new_s. Then next[len] will give the longest same prefix and postfix, in another word, longest palindrome.

I learned the KMP algorithm from http://blog.csdn.net/v_july_v/article/details/7041827.

class Solution {public:    string shortestPalindrome(string s) {        string new_s=s;        reverse(new_s.begin(),new_s.end());        new_s=s+'#'+new_s;//to avoid error if s is empty or s is something like "aaa"        int len=new_s.size();        vector<int> next(len+1);        next[0]=-1;        int k=-1,j=0;        while(j<len)        {            if(k==-1||new_s[k]==new_s[j])                next[++j]=++k;            else                k=next[k];        }        int idx=next[len];        string temp=s.substr(idx);        reverse(temp.begin(),temp.end());        return temp+s;    }};


0 0
原创粉丝点击