***Shortest Palindrome

来源:互联网 发布:企业文档数据加密 编辑:程序博客网 时间:2024/05/16 02:59

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".

Credits:

Special thanks to @ifanchu for adding this problem and creating all test cases. Thanks to @Freezen for additional test cases.

分析:

好像做某个公司笔试题目的时候遇到过这个题目

https://leetcode.com/discuss/36807/c-8-ms-kmp-based-o-n-time-%26-o-n-memory-solution

用一些比较巧妙的方法来解。这里我们用到了KMP算法,KMP算法是一种专门用来匹配字符串的高效的算法,具体方法可以参见这篇博文从头到尾彻底理解KMP。我们把s和其转置r连接起来,中间加上一个其他字符,形成一个新的字符串t,我们还需要一个和t长度相同的一位数组p,其中p[i]表示从t[i]到开头的子串的相同前缀后缀的个数,具体可参考KMP算法中解释。最后我们把不相同的个数对应的字符串添加到s之前即可

class Solution {public:    string shortestPalindrome(string s) {        string r = s;        reverse(r.begin(), r.end());        string t = s + "#" + r;        vector<int> p(t.size(), 0);        for (int i = 1; i < t.size(); ++i) {            int j = p[i - 1];            while (j > 0 && t[i] != t[j]) j = p[j - 1];            p[i] = (j += t[i] == t[j]);        }        return r.substr(0, s.size() - p[t.size() - 1]) + s;    }};


参考代码如下:

public class Solution {     public String shortestPalindrome(String s) {        if(s.length() <= 1){ return s; }        String curs = s + " " + new StringBuilder(s).reverse().toString();        int[] trace = new int[curs.length()];        for(int i = 1 ; i < curs.length() ; i++){            int curindex = trace[i-1];            while(curindex > 0 && curs.charAt(curindex) != curs.charAt(i)){                curindex = trace[curindex-1];            }            if(curs.charAt(curindex) == curs.charAt(i)){                trace[i] = curindex+1;            }        }        return new StringBuilder(s.substring(trace[curs.length()-1])).reverse().toString() + s;     }}


0 0
原创粉丝点击