-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathKMPStringMatching.java
97 lines (89 loc) · 1.58 KB
/
KMPStringMatching.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
94
95
96
97
import java.util.Scanner;
public class KMPStringMatching{
String text = "";
String pattern = "";
int tLen,pLen,count=0; //textLength, patternLength, numOfMatches
int[] lps; //LONGEST PREFIX SUFFIX
void inputData()
{
Scanner sc = new Scanner(System.in);
System.out.print("\nEnter Text String: ");
text = sc.next();
System.out.print("Enter Pattern String: ");
pattern = sc.next();
tLen = text.length();
pLen = pattern.length();
lps = new int[pLen];
}
void lpsArray()
{
lps[0] = 0; //LPS[0] ID ALWAYS 0
int i=1; //to index through pattern from 1 to pLen-1
int len=0;
while(i<pLen)
{
if(pattern.charAt(len) == pattern.charAt(i))
{
len++;
lps[i] = len;
i++;
}
else
{
if(len != 0)
{
len = lps[len-1];
}
else
{
lps[i] = len;
i++;
}
}
}
}
void kmpSearch()
{
int i=0;//index for text
int j=0;//index for pattern
while(i<tLen)
{
if(pattern.charAt(j) == text.charAt(i))
{
i++;
j++;
}
//If the patern match is found (0 to pLen-1 matched), print answer
if(j==pLen)
{
System.out.printf("\nPattern found at index %d",i-j);
count++;
//IMPORTANT STEP
j = lps[j-1];
}
//If encountered a mismatch
if(i<tLen && pattern.charAt(j) != text.charAt(i))
{
if(j != 0)
{
j = lps[j-1];
}
else
{
i++;
}
}
}
if(count==0)
{
System.out.println("NO MATCH FOUND");
}
}
public static void main(String args[])
{
KMPStringMatching obj = new KMPStringMatching();
obj.inputData();
obj.lpsArray();
obj.kmpSearch();
}
}