MCPcopy Create free account
hub / github.com/PrajaktaSathe/Java / KMP

Class KMP

Programs/KMP.java:1–59  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

1class KMP{
2 String string;
3 String pattern;
4 int[] lps;
5
6 KMP(String string,String pattern){
7 this.string = string;
8 this.pattern = pattern;
9 this.lps = new int[pattern.length()];
10 }
11
12
13 public int kmp() {
14 this.createLPS();
15 int i = 0,j= 0;
16
17 while(i<this.string.length() && j<this.pattern.length()) {
18 if(this.string.charAt(i) == this.pattern.charAt(j)) {
19 i++;
20 j++;
21 }
22 else if(j==0) {
23 i++;
24 }
25 else {
26 j = this.lps[j-1];
27 }
28
29 }
30
31 if(j==pattern.length()) {
32 return i-pattern.length();
33 }
34
35
36 return -1;
37 }
38
39
40 private void createLPS() {
41 int i=0,j=1;
42 this.lps[0] = 0;
43
44 while(j<this.pattern.length()) {
45 if(this.pattern.charAt(i) == this.pattern.charAt(j)) {
46 this.lps[j] = i+1;
47 i++;
48 j++;
49 }
50 else if(i ==0) { //this is same as because we wont reach this part if they are not equal, this.pattern.charAt(i) != this.pattern.charAt(j) && i ==0
51 this.lps[j] = 0;
52 j++;
53 }
54 else {
55 i = this.lps[i-1];
56 }
57 }
58 }
59}
60public class Main{

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected