給定兩個字符串 A 和 B, 尋找重複疊加字符串A的最小次數,使得字符串B成爲疊加後的字符串A的子串,若是不存在則返回 -1java
舉個例子,A = "abcd",B = "cdabcdab"。 答案爲 3, 由於 A 重複疊加三遍後爲 「abcdabcdabcd」,此時 B 是其子串;A 重複疊加兩遍後爲"abcdabcd",B 並非其子串。app
A 與 B 字符串的長度在1和10000區間範圍內學習
先找出終止條件,也就是找出A
複製的最大字符串長度。當A
的長度大於B
的長度時,A
複製兩次沒有包含B
字符串的話,後面也不可能包含了,這種狀況下的最大長度爲2*A.length
。當A
的長度小於B
的長度時,複製A
的字符串長度爲A.length+B.length
時,A
字符串沒有包含B
字符串,則後面也不會包含,此時的最大長度爲A.length+B.length
。結合二者取最大值A.length*2+B.length
。ui
public static int repeatedStringMatch(String A, String B) {
// 最大字符串長度
int max_length = (A.length()*2 + B.length()) < 10000 ? (A.length()*2 + B.length()) : 10000;
// 複製A
StringBuilder sb = new StringBuilder(A);
// 重複次數
int repeated_count = 1;
while (sb.length()<= max_length){
if (sb.lastIndexOf(B) > -1){
return repeated_count;
}
repeated_count++;
sb.append(A);
}
return -1;
}
複製代碼