-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAddToFrontPalindrome.java
More file actions
39 lines (32 loc) · 955 Bytes
/
AddToFrontPalindrome.java
File metadata and controls
39 lines (32 loc) · 955 Bytes
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
package String;
public class AddToFrontPalindrome {
public static int[] computeLPSArray(String str) {
int n = str.length();
int[] lps = new int[n];
int i = 1, len = 0;
lps[0] = 0;
while (i < n) {
if (str.charAt(i) == str.charAt(len)) {
len++;
lps[i] = len;
i++;
} else {
if (len != 0) {
len = lps[len - 1];
} else {
lps[i] = 0;
i++;
}
}
}
return lps;
}
static int getMinCharToAddedToMakeStringPalindrome(String str) {
StringBuilder s = new StringBuilder();
s.append(str);
String rev = s.reverse().toString();
s.reverse().append("$").append(rev);
int[] lps = computeLPSArray(s.toString());
return str.length() - lps[s.length() - 1];
}
}