-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathProblem_19.java
More file actions
70 lines (59 loc) · 1.92 KB
/
Problem_19.java
File metadata and controls
70 lines (59 loc) · 1.92 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
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
package strings;
//* KMP algo
public class Problem_19 {
public static void search(String text, String pattern) {
int n = text.length();
int m = pattern.length();
// Preprocess the pattern to compute the longest prefix-suffix (LPS) array
int[] lps = computeLPSArray(pattern);
int i = 0; // index for text
int j = 0; // index for pattern
while (i < n) {
if (text.charAt(i) == pattern.charAt(j)) {
i++;
j++;
}
if (j == m) {
// Pattern found at index i - j
System.out.println("Pattern found at index " + (i - j));
j = lps[j - 1]; // Shift the pattern using LPS
} else if (i < n && text.charAt(i) != pattern.charAt(j)) {
// Mismatch occurred, use LPS
if (j != 0) {
j = lps[j - 1];
} else {
i++;
}
}
}
}
private static int[] computeLPSArray(String pattern) {
int m = pattern.length();
int[] lps = new int[m];
int len = 0; // length of the previous longest prefix suffix
lps[0] = 0; // lps[0] is always 0
int i = 1;
while (i < m) {
if (pattern.charAt(i) == pattern.charAt(len)) {
len++;
lps[i] = len;
i++;
} else {
// mismatch occurred, check previous prefix if any
if (len != 0) {
len = lps[len - 1];
} else {
// No prefix found, set lps[i] to 0
lps[i] = 0;
i++;
}
}
}
return lps;
}
public static void main(String[] args) {
String text = "ABABDABACDABABCABAB";
String pattern = "ABABCABAB";
search(text, pattern);
}
}