-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmininsertionfrontpalindrome.java
71 lines (57 loc) · 1.31 KB
/
mininsertionfrontpalindrome.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
67
68
69
70
71
package strings;
public class mininsertionfrontpalindrome {
public static void main(String[] args) {
// TODO Auto-generated method stub
// System.out.println(palindrome("abc"));
// System.out.println(palindrome("AACECAAAA"));
// System.out.println(palindrome("namand"));
palinromeoptimised("abc");
}
// O(n2)->time
public static int palindrome(String s) {
int j = s.length() - 1;
while (j > 0) {
if (checkpalindrome(s, j)) {
return s.length() - j - 1;
} else {
j--;
}
}
return s.length() - 1;
}
public static boolean checkpalindrome(String s, int j) {
int i = 0;
while (i <= j) {
if (s.charAt(i) != s.charAt(j)) {
return false;
} else {
j--;
i++;
}
}
return true;
}
public static void palinromeoptimised(String s) {
String temp = s + "@";
for (int i = s.length() - 1; i >= 0; i--) {
temp += s.charAt(i);
}
System.out.println(temp);
int[] pitable = new int[temp.length() + 1];
int i = 0, j = -1;
pitable[0] = -1;
while (i < temp.length()) {
while (j >= 0 && temp.charAt(i) != temp.charAt(j)) {
j = pitable[j];
}
i++;
j++;
pitable[i] = j;
}
for (int k = 0; k < pitable.length; k++) {
System.out.println(pitable[k]);
}
System.out.println(s);
System.out.println("ans " + (s.length() - pitable[temp.length()]));
}
}