public class KMPTest {
public static void main(String[] args) {
String s = "abababb";
String t = "abb";
int m = s.length(), n = t.length();
s = " " + s;
t = " " + t;
char[] sArr = s.toCharArray();
char[] tArr = t.toCharArray();
int[] ne = new int[n+1];
int pos = -1;
for(int i=2,j=0;i<=n;i++) {
while(j != 0 && tArr[i] != tArr[j+1]) j = ne[j];
if(tArr[i] == tArr[j+1]) j++;
ne[i] = j;
}
for(int i=1, j=0; i<=m;i++)
{
while(j!=0 && sArr[i] != tArr[j+1]) j = ne[j];
if(sArr[i] == tArr[j+1]) j++;
if(j == n) {
pos = i - n;
break;
}
}
if(pos == -1) System.out.println("Not Found");
else System.out.println("Found, pos = " + pos);
}
}