Description
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.
Solution
对于String A = "abcd"
我们考虑这三个例子:String B = "abcdabcdabcd"
、String B = "abcdabcdab"
、String B = "cdabcdabcdab"
。
在第一种情况中,A和B是完全相同的字符串,因此只需要重复字符串A三次即可得到B;在第二种情况中,B的前两个abcd
是与A一模一样的,而第三个只有ab
没有cd
,此时依然需要重复字符串A三次,B才为A的子字符串;对于第三种情况则比较特殊,虽然它也包含了三个abcd
,但有一个abcd
是被拆分到头部和尾部的,也就相当于第二种情况的头部再加上一个cd
,此时需要重复字符串A四次。
根据以上分析,我们先重复字符串A直到它的长度大于或等于字符串B,这时候判断字符串B是否为字符串A的子字符串,如果判断为否,说明字符串B不属于第一二种情况,则再重复一遍字符串判断其是否为第三种情况,如果是的话则返回遍数,如果不是就说明没有结果,返回-1。
class Solution {
public int repeatedStringMatch(String A, String B) {
StringBuilder sb = new StringBuilder(A);
int count = 1;
while(sb.length() < B.length()) {
sb.append(A);
count++;
}
if(sb.toString().contains(B)) return count;
if(sb.append(A).toString().contains(B)) return count+1;
return -1;
}
}