码迷,mamicode.com
首页 > 编程语言 > 详细

Java for LeetCode 214 Shortest Palindrome

时间:2015-06-09 21:40:38      阅读:1582      评论: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.

For example:

Given "aacecaaa", return "aaacecaaa".

Given "abcd", return "dcbabcd".

解题思路:

本题最简单的思路是从后往前判断子串是否是回文串,然后把后面的弄到前面即可,不过这样仅仅能擦边通过测试,最高效的当然是KMP算法了,

KMP可以参考Java for LeetCode 028 Implement strStr()

JAVA实现如下;

    public String shortestPalindrome(String s) {
        for(int i=s.length();i>=1;i--)
        	if(isPalindrome(s.substring(0, i)))
        		return new StringBuilder(s.substring(i)).reverse()+s;
        return "";
    }
    static boolean isPalindrome(String s){
    	int left=0,right=s.length()-1;
    	while(left<right)
    		if(s.charAt(left++)!=s.charAt(right--))
    			return false;
    	return true;
    }

 

Java for LeetCode 214 Shortest Palindrome

标签:

原文地址:http://www.cnblogs.com/tonyluis/p/4564526.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!