天题系列: Shortest Palindrome

今天完整刷完leetcode除了自己看不懂follow不下来的 199道题。。。纪念一下

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那种怪东东

完全抄自leetcode讨论http://www.programcreek.com/2014/06/leetcode-shortest-palindrome-java/

Analysis

We can solve this problem by using one of the methods which is used to solve the longest palindrome substring problem.

Specifically, we can start from the center and scan two sides. If read the left boundary, then the shortest palindrome is identified.

Java Solution

public String shortestPalindrome(String s) {
	if (s == null || s.length() <= 1)
		return s;
 
	String result = null;
 
	int len = s.length();
	int mid = len / 2;	
 
	for (int i = mid; i >= 1; i--) {
		if (s.charAt(i) == s.charAt(i - 1)) {
			if ((result = scanFromCenter(s, i - 1, i)) != null)
				return result;
		} else {
			if ((result = scanFromCenter(s, i - 1, i - 1)) != null)
				return result;
		}
	}
 
	return result;
}
 
private String scanFromCenter(String s, int l, int r) {
	int i = 1;
 
	//scan from center to both sides
	for (; l - i >= 0; i++) {
		if (s.charAt(l - i) != s.charAt(r + i))
			break;
	}
 
	//if not end at the beginning of s, return null 
	if (l - i >= 0)
		return null;
 
	StringBuilder sb = new StringBuilder(s.substring(r + i));
	sb.reverse();
 
	return sb.append(s).toString();
}
posted @ 2015-06-18 03:33  世界到处都是小星星  阅读(281)  评论(0编辑  收藏  举报