-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathComputeLpsArray.java
More file actions
44 lines (37 loc) · 1.03 KB
/
ComputeLpsArray.java
File metadata and controls
44 lines (37 loc) · 1.03 KB
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
import java.util.Arrays;
/**
* LPS - Longest prefix which is also a suffix
* Used in KMP algorithm
*/
public class ComputeLpsArray {
public static void main(String[] args) {
String pattern = "AAACAAAAAC";
int[] lps = computeLpsArray(pattern);
System.out.println("LPS array: " + Arrays.toString(lps));
}
public static int[] computeLpsArray(String pattern) {
int[] lps = new int[pattern.length()];
int len = 0;
int i = 1;
int n = pattern.length();
lps[0] = 0;
while (i < n) {
if (pattern.charAt(i) == pattern.charAt(len)) {
len++;
lps[i] = len;
i++;
}
else {
// For cases like AAACAAAA, when we have to backtrack
if (len != 0) {
len = lps[len - 1];
}
else {
lps[i] = 0;
i++;
}
}
}
return lps;
}
}