版权声明:码字不易,转载请注明出处: https://blog.csdn.net/qq_24309981/article/details/90263593
1 描述
Description
- 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.
Example
- input: A = “abcd” and B = “cdabcdab”.
- output: 3
- Explain:
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.
2 代码
#include <iostream>
#include <string>
using namespace std;
int repeatedStringMatch(string A, string B) {
int res = -1;
int N = B.size() / A.size() - (!(B.size() % A.size()));
string temp = "";
for (int i = 0; i < N; i++)
{
temp += A;
}
for (int i = 1; i < 3; i++)
{
temp += A;
if (temp.find(B) != string::npos)
{
res = N + i;
break;
}
}
return res;
}
int main()
{
string A = "abcd";
string B = "cdabcdab";
int res = repeatedStringMatch(A, B);
cout << res << endl;
system("pause");
return 0;
}
3 解释
重复A,得到字符串C
- 只有当 C 的长度 大于等于 B时,B才有成为 C 子串的可能;
- C 的长度上限为(A的长度 + B的长度),无限制地增加C的长度是无意义的。