Ai
1 Star 0 Fork 0

徐长贺/Leetcode

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
_214.java 2.48 KB
一键复制 编辑 原始数据 按行查看 历史
Fisher Coder 提交于 2018-09-23 23:00 +08:00 . refactor 214
package com.fishercoder.solutions;
/**
214. Shortest Palindrome
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".
*/
public class _214 {
public static class Solution1 {
/**credit: https://discuss.leetcode.com/topic/27261/clean-kmp-solution-with-super-detailed-explanation*/
/**
* TODO: read it explanation and understand KMP completely.
*/
public String shortestPalindrome(String s) {
String temp = s + "#" + new StringBuilder(s).reverse().toString();
int[] table = getTable(temp);
//get the maximum palin part in s starts from 0
return new StringBuilder(s.substring(table[table.length - 1])).reverse().toString() + s;
}
public int[] getTable(String s) {
//get lookup table
int[] table = new int[s.length()];
//pointer that points to matched char in prefix part
int index = 0;
//skip index 0, we will not match a string with itself
for (int i = 1; i < s.length(); i++) {
if (s.charAt(index) == s.charAt(i)) {
//we can extend match in prefix and postfix
table[i] = table[i - 1] + 1;
index++;
} else {
//match failed, we try to match a shorter substring
//by assigning index to table[i-1], we will shorten the match string length, and jump to the
//prefix part that we used to match postfix ended at i - 1
index = table[i - 1];
while (index > 0 && s.charAt(index) != s.charAt(i)) {
//we will try to shorten the match string length until we revert to the beginning of match (index 1)
index = table[index - 1];
}
//when we are here may either found a match char or we reach the boundary and still no luck
//so we need check char match
if (s.charAt(index) == s.charAt(i)) {
//if match, then extend one char
index++;
}
table[i] = index;
}
}
return table;
}
}
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/isulong/Leetcode.git
git@gitee.com:isulong/Leetcode.git
isulong
Leetcode
Leetcode
master

搜索帮助