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
  • 相关阅读:
    Java 8实战之读书笔记五:超越Java 8
    Quartz的简单使用
    Quartz实现数据库动态配置定时任务
    Java解析Groovy和Shell的代码
    Spring学习笔记(3)——快速入门
    linux的防火墙端口配置
    气泡提示 纯CSS
    解决LINUX下SQLPLUS时上下左右键乱码问题
    redhat Enterprise Linux 6 VNC安装
    使用mount命令挂载CDROM
  • 原文地址:https://www.cnblogs.com/amazingzoe/p/5887354.html
Copyright © 2011-2022 走看看