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. 但后來發(fā)現(xiàn)這樣做有可能導(dǎo)致while循環(huán)無限循環(huán)下去,因為對于那種A不管循環(huán)多少次夕春,都不可能包含B的情況沒有寫終止條件专挪。我卡在了不知道如何判斷這種永遠不可能包含的情況∷俪蓿看了答案發(fā)現(xiàn)其實只需要觀察一下就可以寫出判斷條件:首先保證sb的長度要至少大于等于B, 不然B不可能成為sb的substring. 不過僅僅保證這個條件還是不夠,比如sb = cdabcdab, B = abcdabcd, 這種情況就是雖然A和B長度相等冶共,但起始字符不一樣捅僵,這樣也會導(dǎo)致A里面找不到B. 這種情況下只要再循環(huán)一遍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;
}
}