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.
如果A*N.contains(B),那么求出最小的N,如果没有返回-1
public int repeatedStringMatch(String A, String B) {
StringBuilder sb = new StringBuilder();
int result = 0;
/**
* 重复拼接A直到长度大于B,这时候才有可能A.contains(B)
*/
while (sb.length() < B.length()){
sb.append(A);
result++;
}
/**
* 如果A.contains(B),返回结果
*/
if(sb.toString().contains(B)){
return result;
}
/**
* 再追加一次A可以cover题目中给出的那种类似于B字符串的情况
*/
if(sb.append(A).toString().contains(B)){
return ++result;
}
return -1;
}