Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
72 changes: 72 additions & 0 deletions KMP.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
public class KMP {

public boolean hasSubstring(char[] text, char[] pattern){
int i=0;
int j=0;
int k = 0;
while(i < text.length && j < pattern.length){
if(text[i] == pattern[j]){
i++;
j++;
}else{
j=0;
k++;
i = k;
}
}
if(j == pattern.length){
return true;
}
return false;
}
private int[] computeTemporaryArray(char pattern[]){
int [] lps = new int[pattern.length];
int index =0;
for(int i=1; i < pattern.length;){
if(pattern[i] == pattern[index]){
lps[i] = index + 1;
index++;
i++;
}else{
if(index != 0){
index = lps[index-1];
}else{
lps[i] =0;
i++;
}
}
}
return lps;
}
public boolean KMP(char []text, char []pattern){
int lps[] = computeTemporaryArray(pattern);
int i=0;
int j=0;
while(i < text.length && j < pattern.length){
if(text[i] == pattern[j]){
i++;
j++;
}else{
if(j!=0){
j = lps[j-1];
}else{
i++;
}
}
}
if(j == pattern.length){
return true;
}
return false;
}

public static void main(String args[]){

String str = "abcxabcdabcdabcy";
String subString = "abcdabcy";
KMP ss = new KMP();
boolean result = ss.KMP(str.toCharArray(), subString.toCharArray());
System.out.print(result);

}
}