public int indexOf(String s, String m) { if (s == null || m == null || m.length() < 1 || s.length() < 1 || s.length() < m.length()) return -1; char[] ss = s.toCharArray(); char[] ms = m.toCharArray(); int si = 0, mi = 0; int[] next = nextIndex(ms); while (si < ss.length && mi < ms.length) { if (mi == -1 || ss[si] == ms[mi]) { si++; mi++; } else { mi = next[mi]; } } return mi == ms.length ? si - mi : -1; } public int[] nextIndex(char[] str) { if (str.length == 1) return new int[]{-1}; int[] next = new int[str.length]; next[0] = -1; next[1] = 0; int pos = 2; int cn = 0; while (pos < next.length) { if (str[pos - 1] == str[cn]) { next[pos++] = ++cn; } else if (cn > 0) { cn = next[cn]; } else { next[pos++] = 0; } } return next; }