package test;
public class StringKMP {
public void getNextBetter(String str, int[] next){
int len = str.length();
next[1] = 0;
int i = 1;
int j = 0;
while(i < len - 1){
if(j == 0 || str.charAt(i) == str.charAt(j)){
++ i;
++ j;
if(str.charAt(i) != str.charAt(j)){
next[i] = j;
} else{
next[i] = next[j];
}
} else {
j = next[j];
}
}
}
public void getNext(String str, int[] next){
int len = str.length();
next[1] = 0;
int i = 1;
int j = 0;
while(i < len - 1){
if(j == 0 || str.charAt(i) == str.charAt(j)){
++ i;
++ j;
next[i] = j;
} else {
j = next[j];
}
}
}
public int getIndex(String strLong, String strShort, int pos){
int lenLong = strLong.length();
int lenShort = strShort.length();
strLong = "x" + strLong;
strShort = "x" + strShort;
int[] next = new int[lenShort + 1];
this.getNextBetter(strShort, next);
int i = pos + 1;
int j = 1;
while(i <= lenLong && j <= lenShort){
if(j == 0 || strLong.charAt(i) == strShort.charAt(j)){
++ i;
++ j;
} else{
j = next[j];
}
}
if(j > lenShort)
return i-lenShort-1;
else
return 0;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
String strLong = "ertsafabaabcacseadfsdg";
String strShort = "abaabcac";
StringKMP kmp = new StringKMP();
int index = kmp.getIndex(strLong,strShort,0);
System.out.println(index);
}
}
public class StringKMP {
public void getNextBetter(String str, int[] next){
int len = str.length();
next[1] = 0;
int i = 1;
int j = 0;
while(i < len - 1){
if(j == 0 || str.charAt(i) == str.charAt(j)){
++ i;
++ j;
if(str.charAt(i) != str.charAt(j)){
next[i] = j;
} else{
next[i] = next[j];
}
} else {
j = next[j];
}
}
}
public void getNext(String str, int[] next){
int len = str.length();
next[1] = 0;
int i = 1;
int j = 0;
while(i < len - 1){
if(j == 0 || str.charAt(i) == str.charAt(j)){
++ i;
++ j;
next[i] = j;
} else {
j = next[j];
}
}
}
public int getIndex(String strLong, String strShort, int pos){
int lenLong = strLong.length();
int lenShort = strShort.length();
strLong = "x" + strLong;
strShort = "x" + strShort;
int[] next = new int[lenShort + 1];
this.getNextBetter(strShort, next);
int i = pos + 1;
int j = 1;
while(i <= lenLong && j <= lenShort){
if(j == 0 || strLong.charAt(i) == strShort.charAt(j)){
++ i;
++ j;
} else{
j = next[j];
}
}
if(j > lenShort)
return i-lenShort-1;
else
return 0;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
String strLong = "ertsafabaabcacseadfsdg";
String strShort = "abaabcac";
StringKMP kmp = new StringKMP();
int index = kmp.getIndex(strLong,strShort,0);
System.out.println(index);
}
}