LeetCode题解——Shortest Palindrome

来源:互联网 发布:网络棋牌作弊器下载 编辑:程序博客网 时间:2024/05/17 22:52

题目:

在一个字符串s的前面添加最少的字符使得该字符串变为回文字符串。

解题思路:

改题可以等价为求解以s[0]为开始节点的最长回文子串,比如s[0] - s[10] 是s中以s[0]为头的最长回文子串,那么截取s[11]到s[end] ,记为 t,然后反转t,即为所求。


class Solution {public:    string shortestPalindrome(string s){        int sz = s.size();        if(sz<2) return s;        int L,R,longestprefix = 1;        for(int i=0; i<(sz+1)/2;){            L = i; R = i;            while(R<sz-1 && s[R]==s[R+1]) R++;            i=R+1;            while(L>0 && R<sz-1 && s[L-1]==s[R+1]){L--;R++;}            if(L==0 && longestprefix<R-L+1){                longestprefix = R-L+1;            }        }        auto t = s.substr(longestprefix);        reverse(t.begin(),t.end());        return t+s;    }};


0 0