-
Notifications
You must be signed in to change notification settings - Fork 153
/
KMPAlgo.java
76 lines (63 loc) · 1.05 KB
/
KMPAlgo.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
/**
* @date 06/01/1998
* @author spattk (Sitesh Pattanaik)
*/
import java.util.*;
class StringMatching
{
static int KMPSearch(String text, String subs){
int n = subs.length();
int[] lps = new int[n];
generateLPSArray(lps,subs);
n = text.length();
int m = subs.length();
int i=0,j=0;
while(i<n){
if(text.charAt(i)==subs.charAt(j)){
i++;
j++;
}
if(j==m){
//Pattern Found
return (i-j);
}
else if(i<n && text.charAt(i)!=subs.charAt(j)){
if(j!=0){
j = lps[j-1];
}
else{
i++;
}
}
}
return -1;
}
static void generateLPSArray(int[] lps, String subs)
{
int j = 0;
int i = 1;
int n = subs.length();
while(i<n){
if(subs.charAt(i)==subs.charAt(j)){
j++;
lps[i] = j;
i++;
}
else{
if(j!=0){
j = lps[j-1];
}
else{
lps[i] = 0;
i++;
}
}
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String text = sc.next();
String subs = sc.next();
System.out.println(KMPSearch(text,subs));
}
}