1. 題目原址
https://leetcode.com/problems/repeated-string-match/
2. 題目描述
3. 題目大意
給定兩個字元串,A和B,讓A重複多少次可以讓B變為A的子串。
4. 解題思路
- 首先計算B的長度是A字元串的長度的多少倍count,倍數count(即B的長度不能完全整除A),則将count++
- 然後定義一個StringBuilder類型的變量,讓他重複添加count個A.
- 注意:這個地方有一類測試用例容易忽略,即A = “abcd”, B=“cdabcdab”
5. AC代碼
class Solution {
public int repeatedStringMatch(String A, String B) {
int alen = A.length();
int blen = B.length();
int count = blen / alen;
if(blen % alen != 0) count++;
StringBuilder sb = new StringBuilder();
for(int i = 0; i < count; i++){
sb.append(A);
}
if(!sb.toString().contains(B)){
sb.append(A);
count++;
if(!sb.toString().contains(B)) return -1;
}
return count;
}
}
6. 相似源碼
【1】 459. Repeated Substring Pattern 題目原址:https://leetcode.com/problems/repeated-substring-pattern/