classSolution { publicintrepeatedStringMatch(String a, String b) { StringBuilderbuilder=newStringBuilder(); intans=0, n = a.length(), m = b.length(); while (builder.length() < m) { builder.append(a); ++ans; } builder.append(a); intindex= strStr(builder.toString(), b); if (index == -1) return -1; return index + m > n * ans ? ans + 1 : ans; }
// LC privateintstrStr(String ss, String pp) { intn= ss.length(), m = pp.length(); ss = " " + ss; pp = " " + pp; char[] s = ss.toCharArray(), p = pp.toCharArray(); int[] next = newint[m + 1]; for (inti=1, j = 0; i < m; ) { if (j == 0 || p[i] == p[j]) { ++i; ++j; next[i] = j; } else { j = next[j]; } } inti=1, j = 1; while (i <= n && j <= m) { if (j == 0 || s[i] == p[j]) { ++i; ++j; } else { j = next[j]; } } if (j > m) return i - m - 1; elsereturn -1; } }