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

    Solution TLE,Solution2 AC

    //TLE
    class Solution {
    private:
        bool isPalindrome(string s) {
            int left = 0;
            int right = s.length() - 1;
            while (left < right) {
                if (s[left++] != s[right--])
                    return false;
            }
            return true;
        }
    public:
        string shortestPalindrome(string s) {
            int len = s.length();
            if (len <= 1)
                return s;
    
            int k = 0;
            for (int i = len; i > 0; i--) {
                if (isPalindrome(s.substr(0, i))) {
                    k = i;
                    break;
                }
            }
            string remain = s.substr(k, len - k);
            reverse(remain.begin(), remain.end());
            return remain + s;
        }
    };
    //AC
    class Solution2{
    public:
        string shortestPalindrome(string s){
            int len = s.size();
            if(len <=1) return s;
    
            string v = s;
            reverse(v.begin(),v.end());
    
            int i;
            for (i=len;i>0;i--){
                if( s.substr(0,i) == v.substr(len-i))
                    break;
            }
            return v.substr(0,len-i) + s;
        }
    };
  • 相关阅读:
    flexible
    arcgis
    vue 语法糖
    sass 的安装 编译 使用
    nodeJs
    微信小程序
    linux cgroups 简介
    git命令
    sublime笔记
    工程优化学习(进退法、黄金分割法、二次插值法、三次插值法、最速下降法)
  • 原文地址:https://www.cnblogs.com/wxquare/p/5867577.html
Copyright © 2011-2022 走看看