Easy
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.
这道题我先是想的一直给StringBuilder sb不断地append(A),直到A.indexOf(B) != -1. 但后来发现这样做有可能导致while循环无限循环下去,因为对于那种A不管循环多少次,都不可能包含B的情况没有写终止条件。我卡在了不知道如何判断这种永远不可能包含的情况。看了答案发现其实只需要观察一下就可以写出判断条件:首先保证sb的长度要至少大于等于B, 不然B不可能成为sb的substring. 不过仅仅保证这个条件还是不够,比如sb = cdabcdab, B = abcdabcd, 这种情况就是虽然A和B长度相等,但起始字符不一样,这样也会导致A里面找不到B. 这种情况下只要再循环一遍A,使sb = cdabcdabcdab, 这样就可以确保能找到B了。所以我们判断永远也不可能找到B的条件就是sb.indexOf(B) == -1的时候,判断sb的长度是不是大于A.length() + B.length(),如果是,则说明永远也找不到,直接返回- 1.
public int repeatedStringMatch(String A, String B) {
StringBuilder sb = new StringBuilder(A);
int count = 1;
while (sb.indexOf(B) == -1){
if (sb.length() - A.length() > B.length()){
return -1;
}
sb.append(A);
count++;
}
return count;
}
}