public class Kmp { public static int[] next; public static void main(String[] args) { System.out.println(match("abcabdaba", "aba")); } public static int match(String s,String t) { if(t==null||s==null||t.length()>s.length()||t.length()==0||s.length()==0) return -1; else { int i = 0;int j = 0; getNext(t); while(i<s.length()&&j<t.length()) { if(j==-1||s.charAt(i)==t.charAt(j)) { i++;j++; } else j = next[j]; } if(j>=t.length()) return i-t.length(); else return -1; } } public static void getNext(String t) { int k = -1; int j = 0; next = new int[t.length()]; next[0] = -1; while(j<t.length()-1) { if(k==-1||t.charAt(k)==t.charAt(j)) { ++k;++j; if(t.charAt(j)!=t.charAt(k)) next[j] = k; else next[j] = next[k]; } else k = next[k]; } // for(int m:next) // { // System.out.print(m+" "); // } } }