-
Notifications
You must be signed in to change notification settings - Fork 93
/
kmpAlgorithm.java
93 lines (78 loc) · 1.78 KB
/
kmpAlgorithm.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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
package kmp;
public class kmpAlgorithm {
void computeLPSArray(String pat, int []lps)
{
int j = 0; // length of the previous longest prefix suffix
int i;
lps[0] = 0; // lps[0] is always 0
i = 1;
// the loop calculates lps[i] for i = 1 to M-1
while (i < pat.length())
{
if (pat.charAt(j) == pat.charAt(i))
{
lps[i] = j+1;
i +=1; j+=1;
}
else // (pat[i] != pat[j])
{
if (j != 0)
{
j = lps[j-1];
}
else // if (j == 0)
{
lps[i] = 0;
i++;
}
}
}
}
public void patternSearch(String pattern, String text, int[] lps)
{
int pat_index = 0, text_index = 0;
if(pattern.length() == 0)
{
return;
}
while(text_index < text.length())
{
// if characters match, look for next character match
if(pattern.charAt(pat_index) == text.charAt(text_index))
{
pat_index++; text_index++;
// indicates that complete pattern has matched
if(pat_index == pattern.length())
{
System.out.println("Match");
pat_index = lps[pat_index-1];
}
}
// if the characters do not match, don't go back in the text. Just adjust the pattern_index
else
{
if(pat_index != 0)
{
pat_index = lps[pat_index-1];
}
else
{
text_index++;
}
}
}
}
public static void main(String []args)
{
kmpAlgorithm solution = new kmpAlgorithm();
String pattern = "ananab#banana";
int[] lps = new int[pattern.length()];
solution.computeLPSArray(pattern, lps);
for(int i = 0; i < lps.length; i++)
{
System.out.println(lps[i]);
}
String text = "ananab#banancananab#banana";
solution.patternSearch(pattern, text, lps);
}
}