forked from fishercoder1534/Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
_214.java
66 lines (55 loc) · 2.48 KB
/
_214.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
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;
}
}
}