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

    Analyse: It asks us to get the longest palindrome starting from index 0. Suppose the longest palindrome is s_1, and the original string is s, remaining part is s_2 = s - s_1, then the result should be Reverse(s_2) + s.

    For example, if the string is aaabbbccc, s_1 should be aa, s_2 is abbbccc, the result should be cccbbba|aaabbbccc

    string     aaabbbccc

    s_1       aa

    s_2     abbbccc

    result     cccbbba|aaabbbccc

     

    Start from the back, check if s[0] == s[i] and if s[0...i] is palindrome. If so, compute the result.

    Time limit exceeded. 

     1 class Solution {
     2 public:
     3     string shortestPalindrome(string s) {
     4         if (s.size() < 2) return s;
     5         // find the longest palindrome substring starting from s[0]
     6         int end = 0;
     7         for (int i = s.size() - 1; i >= 0; i--) {
     8             if (s[i] == s[0] && isPalindrome(s, 0, i)) {
     9                 end = i;
    10                 break;
    11             }
    12         }
    13         
    14         // insert [end + 1, s.size() - 1] in front of s in reverse order
    15         string result;
    16         for (int i = s.size() - 1; i > end; i--) 
    17             result += s[i];
    18         result += s;
    19         return result;
    20     }
    21 private:
    22     bool isPalindrome(string s, int start, int end) {
    23         while (start < end) {
    24             if (s[start++] != s[end--]) return false;
    25         }
    26         return true;
    27     }
    28 };
    View Code
  • 相关阅读:
    2.六角星绘制
    1.五角星绘制
    Redis
    javaScript
    反射
    区分'方法'和'函数'
    递归,二分法
    匿名函数,排序函数,过滤函数,映射函数,
    生成器,生成器函数,推导式,生成器表达式.
    函数,闭包,迭代器
  • 原文地址:https://www.cnblogs.com/amazingzoe/p/5887354.html
Copyright © 2011-2022 走看看