您的位置:首页 > 其它

天题系列: Shortest Palindrome

2015-06-18 03:33 316 查看
今天完整刷完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();
}

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: