题目:
Given two strings
A
andB
, find the minimum number of timesA
has to be repeated such thatB
is a substring of it. If no such solution, return-1
.
For example, withA = "abcd"
andB = "cdabcdab"
.
Return 3, because by repeatingA
three times (“abcdabcdabcd”),B
is a substring of it; andB
is not a substring ofA
repeated two times (“abcdabcd”).
Note:
The length ofA
andB
will be between 1 and 10000.
解释:
python代码:
from math import ceil
class Solution(object):
def repeatedStringMatch(self, A, B):
"""
:type A: str
:type B: str
:rtype: int
"""
m=int(ceil(len(B)/float(len(A))))
n=m+1
if B in A*m:
return m
elif B in A*n:
return n
return -1
c++代码:
#include <cmath>
using namespace std;
class Solution {
public:
int repeatedStringMatch(string A, string B) {
int m=ceil(B.size()/(float)A.size())+1;
string tmp=A;
for (int i=0;i<=m;i++)
{
if(tmp.find(B)!=string::npos)
return i+1;
tmp+=A;
}
return -1;
}
};
总结:
要用到向上取整