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

    For example:

    Given "aacecaaa", return "aaacecaaa".

    Given "abcd", return "dcbabcd".

    public class Solution {
        public String shortestPalindrome(String s) {
    /*        其实问题可以转化成求从s[0]开始的最长回文,找到以s[0]开始的最长回文,将剩下的部分倒序补在字符串前面就是答案
            可以从最后一个往前找
    
            先找到的就是以s[0]为开始的最长回文
            此种方法会超时
            TLE
            http://blog.csdn.net/yujin753/article/details/47047155
            */
            if(s==null||s.length()<=0) return null;
            int len=s.length();
            for(;len>0;len--){
                if(isPal(s.substring(0,len)))
                   break;
            }
            if(len!=s.length()){
                StringBuilder seq=new StringBuilder(s.substring(0,len));
                for(int i=len;i<s.length();i++){
                    seq.insert(0,s.charAt(i));
                }
                return seq.toString();
            }
            return s;
        }
        public boolean isPal(String s){
            int start=0;
            int end=s.length()-1;
            while(start<end){
                if(s.charAt(start)!=s.charAt(end)) return false;
                start++;
                end--;
            }
            return true;
        } 
    }
  • 相关阅读:
    POJ2155 Matrix
    POJ3469 Dual Core CPU
    洛谷P1469找筷子
    CodeForces 97D. Robot in Basement
    UVa11542 Square
    清澄 A1485. Catch The Penguins 抓企鹅
    Bzoj2595: [Wc2008]游览计划
    HDU4085 Peach Blossom Spring
    CodeForces 333E. Summer Earnings
    洛谷P3389 【模板】高斯消元法
  • 原文地址:https://www.cnblogs.com/qiaomu/p/4709142.html
Copyright © 2011-2022 走看看