-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathKMP.java
More file actions
58 lines (51 loc) · 1.53 KB
/
KMP.java
File metadata and controls
58 lines (51 loc) · 1.53 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
class KMP {
// Faz a tabela do padrão (o autômato).
private int[] computeLPS(String pattern) {
int length = pattern.length();
int[] lps = new int[length];
// i e j são referentes a qual letra/caractere que o programa deve voltar no
// padrão
int i = 0;
int j = 1;
while (j < length) {
if (pattern.charAt(i) == pattern.charAt(j)) {
lps[j] = i + 1;
i++;
j++;
} else {
if (i != 0) {
i = lps[i - 1];
} else {
lps[j] = 0;
j++;
}
}
}
return lps;
}
// Busca pelo padrão no texto.
public void search(String text, String pattern) {
int textLength = text.length();
int patternLength = pattern.length();
int[] lps = computeLPS(pattern);
int i = 0;
int j = 0;
while (i < textLength) {
if (text.charAt(i) == pattern.charAt(j)) {
i++;
j++;
if (j == patternLength) {
// Resposta para cada instância do padrão encontrado no texto.
System.out.println("Padrão encontrado no índice " + (i - j));
j = lps[j - 1];
}
} else {
if (j != 0) {
j = lps[j - 1];
} else {
i++;
}
}
}
}
}