Leetcode: Repeated String Match

Given two strings A and B, find the minimum number of times A has to be repeated such that B is a substring of it. If no such solution, return -1.

For example, with A = "abcd" and B = "cdabcdab".

Return 3, because by repeating A three times (“abcdabcdabcd”), B is a substring of it; and B is not a substring of A repeated two times ("abcdabcd").

Note:
The length of A and B will be between 1 and 10000.

The idea is to keep string builder and appending until the length A is greater or equal to B.

use a while loop to keep adding A to stringBuilder until sb.length() >= B.length(); see if B is a substring of sb.

why == should break as well?  because it's possible for sb == B. like A = "ABC", B = "ABCABC"

 1 class Solution {
 2     public int repeatedStringMatch(String A, String B) {
 3         StringBuilder sb = new StringBuilder();
 4         int res = 0;
 5         while (sb.length() < B.length()) {
 6             sb.append(A);
 7             res ++;
 8         }
 9         if (sb.toString().contains(B)) return res;
10         if (sb.append(A).toString().contains(B)) return ++res;
11         return -1;
12     }
13 }
原文地址:https://www.cnblogs.com/EdwardLiu/p/11677965.html