//是否匹配或输出第一次匹配的位置 publicclasskmp1{ finalstaticint maxn = (int) 1e7 + 6; publicstaticchar[] a = newchar[maxn]; publicstaticchar[] b = newchar[maxn]; publicstaticint[] ne = newint[maxn];
publicstaticvoidmain(String[] args){ Scanner sc = new Scanner(System.in); String s = sc.next(); a = s.toCharArray(); String ss = sc.next(); b = ss.toCharArray(); System.out.println(kmp(a,b)); }
publicstaticvoidgetnext(char[] x){ ne[0] = -1; int len = x.length; int i = 0, j = -1; while (i < len-1) { if (j == -1 || x[i] == x[j]) { ne[++i] = ++j; } else j = ne[j]; } }
publicstaticintkmp(char[] x, char[] y){ getnext(y); int xlen = x.length; int ylen = y.length; int i = 0, j = 0; int ans = 0; while (i < xlen && j < ylen) { if (j == -1 || x[i] == y[j]) { i++; j++; } else j = ne[j]; } if (j == ylen) return1; // 若 return i-ylen; 为返回第一次匹配时在原串中的位置 else return0; } }