Shortest Palindrome Leetcode Java

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

我的思路:从给定字符串中间一个元素开始向左遍历,判断该位置是否可以作为返回结果的中点/中点右边的元素
时间为392ms
程序如下:

    public String shortestPalindrome(String s) {
        if(s==null||s.length()<2)
            return s;
        int len=s.length();
        int index=(len-1)/2;
        boolean mid=true;
        while(index>=0){
            if(checkMid(s, index, mid)){
                break;
            }
            mid=!mid;
            if(checkMid(s, index, mid))
                break;
            mid=!mid;
            index--;
        }
        System.out.println(index);
        System.out.println(mid);
        StringBuilder rst=new StringBuilder();
        int index2;
        if(mid)
            index2=2*index+1;
        else
            index2=2*(index);
        for(int i=s.length()-1;i>=index2;i--){
            rst.append(s.charAt(i));
        }
        rst.append(s);
        return rst.toString();
    }
    private boolean checkMid(String s, int index,boolean mid){
        int left=index-1;
        int right;
        if(mid)
         right=index+1;     
        else {
            right=index;
        }
        while(left>=0){
            if(s.charAt(left)!=s.charAt(right))
                return false;
            left--;
            right++;
        }
        return true;
    }

但讨论区(https://leetcode.com/discuss/36865/my-java-solution-o-n-2-do-not-need-to-use-manachers-algorithm)中的这个方法,实现起来貌似更简洁一些:
但是效率低一些,时间为856ms

public class Solution {
    public String shortestPalindrome(String s) {
        if(isPalindrome(s))return s;
        int i=s.length();
        while(i>0){
            String sub1 = s.substring(0,i--);
            if(isPalindrome(sub1))break;
        }
        i++;
        String sub2 = s.substring(i);
        StringBuilder sb = new StringBuilder();
        for(int j=sub2.length()-1;j>=0;j--){
            sb.append(sub2.charAt(j));
        }
        for(int j=0;j<s.length();j++){
            sb.append(s.charAt(j));
        }
        return sb.toString();
    }
    private boolean isPalindrome(String s){
        int i=0,j=s.length()-1;
        while(i<j){
            if(s.charAt(i++)!=s.charAt(j--))return false;
        }
        return true;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值