686. 重复叠加字符串匹配
686. Repeated String Match
题目描述
给定两个字符串 A 和 B,寻找重复叠加字符串 A 的最小次数,使得字符串 B 成为叠加后的字符串 A 的子串,如果不存在则返回 -1。
举个例子,A = "abcd",B = "cdabcdab"。
答案为 3,因为 A 重复叠加三遍后为 "abcdabcdabcd",此时 B 是其子串;A 重复叠加两遍后为 "abcdabcd",B 并不是其子串。
注意:
A 与 B 字符串的长度在 1 和 10000 区间范围内。
LeetCode686. Repeated String Match
Java 实现
class Solution {
public int repeatedStringMatch(String A, String B) {
int m = A.length(), n = B.length();
StringBuilder str = new StringBuilder();
for (int i = 1; i <= n / m + 2; i++) {
str.append(A);
if (str.indexOf(B) != -1) {
return i;
}
}
return -1;
}
}
class Solution {
public int repeatedStringMatch(String A, String B) {
int count = 0;
StringBuilder str = new StringBuilder();
while (str.length() < B.length()) {
str.append(A);
count++;
}
if (str.toString().contains(B)) {
return count;
}
if (str.append(A).toString().contains(B)) {
return ++count;
}
return -1;
}
}
相似题目
参考资料