leetcode 214: Shortest Palindrome

Shortest Palindrome

Total Accepted: 172 Total Submissions: 1344

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

[思路]

从某个char开始向两边扩展(左右两边的字符相等), 如果能一直扩展到字符串的头部, 则将末尾余下的reverse,再加到原字符串的头部,即可.

tips:  1. 中轴字符选从中间开始,这样找到的即为最短的. 2. 中轴字符可能为一个, 也可能为两个. 

[CODE]

public class Solution {
    public String shortestPalindrome(String s) {
    	if(s.length()<=1 ) return s;
        int center = (s.length()-1)/2;
        String res="";
        for(int i=center; i>=0; i--) {
        	if(s.charAt(i) == s.charAt(i+1)) {
        		if( (res = check1(s, i, i+1)) !=null) return res;
        	}
    		if( (res = check1(s, i, i)) !=null) return res;

        }
        return res;
    }
    //aabaac
    private String check1(String s, int l, int r) {
    	int i=1;
        for(; l-i>=0 && r+i<s.length(); i++) {
            if(s.charAt(l-i) != s.charAt(r+i) ) break;
        }
        
        if(l-i>=0) return null; 
        StringBuilder sb = new StringBuilder(s.substring(r+i));
        sb.reverse();
        return sb+s;
    }
}


  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 6
    评论
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值