首页 > 其他 > 详细

214. Shortest Palindrome

时间:2020-06-21 10:32:27      阅读:72      评论:0      收藏:0      [点我收藏+]

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.

Example 1:

Input: "aacecaaa"
Output: "aaacecaaa"

Example 2:

Input: "abcd"
Output: "dcbabcd"

class Solution {
    public String shortestPalindrome(String s) {
        if(s == null || s.length() == 0) return s;
        int right = 1;
        for(int i = 2; i <= s.length(); i++){
            if(helper(s.substring(0, i))) right = i;
        }
        if(right == s.length()) return s;
        String front = s.substring(0, right);
        String back = s.substring(right);
        StringBuilder sb = new StringBuilder(back);
        String nback = sb.reverse().toString();
        return nback+front+back;
    }
    public boolean helper(String s){
        int left = 0, right = s.length() - 1;
        while(left < right){
            if(s.charAt(left) != s.charAt(right)) return false;
            left++;
            right--;
        }
        return true;
    }
}

1. brute force

因为只能从front插入,所以先找从前往后最长palindrome,然后剩下的reverse后加到前面

class Solution {
    public String shortestPalindrome(String s) {
        int i = 0, end = s.length() - 1, j = end; char chs[] = s.toCharArray();
        while(i < j) {
             if (chs[i] == chs[j]) {
                 i++; j--;
             } else { 
                 i = 0; end--; j = end;
             }
        }
        return new StringBuilder(s.substring(end+1)).reverse().toString() + s;
    }
}

https://leetcode.com/problems/shortest-palindrome/discuss/60106/My-9-lines-three-pointers-Java-solution-with-explanation

214. Shortest Palindrome

原文:https://www.cnblogs.com/wentiliangkaihua/p/13171402.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!