686.repeated-string-match.go 337 B

12345678910111213
  1. func repeatedStringMatch(A string, B string) int {
  2. m, n, l := len(A), len(B), len(A)
  3. var sb strings.Builder
  4. for cnt := 1; ; cnt, l = cnt+1, l+m {
  5. sb.WriteString(A)
  6. if strings.Index(sb.String(), B) != -1 {
  7. return cnt
  8. } else if n + m < l { // If l > n + m, then each repeat of A is the same for B.
  9. break
  10. }
  11. }
  12. return -1
  13. }