zoukankan      html  css  js  c++  java
  • LeetCode-214 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.

    题目大意

    给定一个字符串,可以在该字符串前加入任何字符,要求在经过若干操作之后,能使得该字符串成为回文串的最小长度的字符串,并返回该字符串。

    示例

    E1

    Input: "aacecaaa"
    Output: "aaacecaaa"

    E2

    Input: "abcd"
    Output: "dcbabcd"

    解题思路

    思路来源于LeetCode@Sammax,将字符串的倒序和该字符串拼接在一起,并对该组合字符串进行KMP的next数组求解,可得到最终结果。

    复杂度分析

    时间复杂度:O(N)

    空间复杂度:O(N)

    代码

    class Solution {
    public:
        string shortestPalindrome(string s) {
            string tmp = s;
            //求字符串的倒序
            reverse(tmp.begin(), tmp.end());
            //将正序与倒序进行拼接,中间应加入一个特殊字符,为了避免next数组计算时产生    
            //错误
            string str = s + "#" + tmp;
            vector<int> next(str.length(), 0);
            //进行KMP算法,next数组计算
            for(int i = 1, k = 0; i < str.length(); ++i) {
                while(k > 0 && str[i] != str[k])
                    k = next[k - 1];
                if(str[i] == str[k])
                    ++k;
                next[i] = k;
            }
    
            return tmp.substr(0, tmp.size() - next[str.size() - 1]) + s;
        }
    };    
  • 相关阅读:
    ASP.NET MVC 3: Razor中的@:和语法
    如何设置VS的代码智能提示
    七次
    不知不觉
    一切一切
    什么是喜欢
    Oracle的substr函数简单用法与substring区别
    前端必读:浏览器内部工作原理(转载)
    sublime text 插件安装 Mac版的
    一个随机上翻的小效果
  • 原文地址:https://www.cnblogs.com/heyn1/p/11052330.html
Copyright © 2011-2022 走看看