zoukankan      html  css  js  c++  java
  • 【Leetcode】Shortest Palindrome

    Shortest Palindrome

    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.

    转载自陆草纯。

    首先确认一点基本知识,如果某个字符串str是回文的,那么str == reverse(str)

    因此,将s逆转之后拼接在s后面,即news=s+reverse(s),该新字符串news首尾相同的部分,即为s中以s[0]为起始的最长回文子串pres

    只不过这里我不用上述的遍历来做,而用类似KMP算法求next数组来做。

    在KMP算法中求next数组就是s自我匹配的过程,next[i]的值就表示s[i]之前有几个元素是与s开头元素相同的。

    因此,next[news.size()]的值就表示news中首尾相同的部分的长度。接下来就好做了。

    注意:当next[news.size()]的值大于s.size()时,说明重复部分贯穿了s与reverse(s),应该修正为next[news.size()]+1-s.size()

    ------------------------------------------------------------------------------------------------------------------------------------------------------------

    class Solution {
    public:
        string shortestPalindrome(string s) {
            if(s == "")
                return s;
            string s2 = s;
            reverse(s2.begin(), s2.end());
            string news = s + s2;
            int n = news.size();
            vector<int> next(n+1);
            buildNext(news, next, n);
            if(next[n] > s.size())
                next[n] = next[n] + 1 - s.size();
            string pres = s.substr(next[n]);
            reverse(pres.begin(), pres.end());
            return pres + s;
        }
        void buildNext(string& s, vector<int>& next, int n)
        {
            int k = -1;
            int j = 0;
            next[0] = -1;
            while(j < n)
            {
                if(k == -1 || s[j] == s[k])
                {
                    k ++;
                    j ++;
                    next[j] = k;
                }
                else
                {
                    k = next[k];
                }
            }
        }
    };
  • 相关阅读:
    linux ubuntu系统安装及卸载oracle xe11.2.0
    32位和64位的应用软件区别是什么
    在Ubuntu Server下安装Oracle XE
    虚拟化系列Citrix XenServer 6.1 安装与配置
    Oracle: listener.ora 、sqlnet.ora 、tnsnames.ora的配置及例子
    敏捷开发资料站推荐
    win7中竟然没有telnet.exe??
    Eclipse+Tomcat+Ant 小记
    为已有的web project项目加入maven支持,并使用myeclipse的插件.
    .NET性能优化数据库方面的总结
  • 原文地址:https://www.cnblogs.com/LUO77/p/5603827.html
Copyright © 2011-2022 走看看