-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.java
43 lines (35 loc) · 1.1 KB
/
Solution.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
class Solution {
public String shortestPalindrome(String s) {
if (s == null || s.length() <= 1) {
return s;
}
String reversed = new StringBuilder(s).reverse().toString();
String combined = s + "#" + reversed;
int[] lps = computeLPS(combined);
int longestPrefix = lps[lps.length - 1];
String suffix = s.substring(longestPrefix);
String prefix = new StringBuilder(suffix).reverse().toString();
return prefix + s;
}
private int[] computeLPS(String s) {
int n = s.length();
int[] lps = new int[n];
int length = 0;
int i = 1;
while (i < n) {
if (s.charAt(i) == s.charAt(length)) {
length++;
lps[i] = length;
i++;
} else {
if (length > 0) {
length = lps[length - 1];
} else {
lps[i] = 0;
i++;
}
}
}
return lps;
}
}