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.
For example, with A = “abcd” and B = “cdabcdab”.
Return 3, 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.
思路1:
用取余的方法循环扫描A,如果B大小8,A大小4,那扫描3次A就够了,所以用个as/bs+2表示扫描几个A,在用次数乘B的大小表示要扫描的字母,t为每个字符下标
class Solution {
public:
int repeatedStringMatch(string A, string B) {
int times=0;
int ai=0,bi=0;
int as=A.size(),bs=B.size();
int m=bs*(as/bs+2);
int t=1;
while(t<m){
if(ai==0){
ct++;
}
if(A[ai]!=B[bi]){
ai=(ai+1)%as;
bi=0;
times=1;
}
if(A[ai]==B[bi]){
ai=(ai+1)%as;
bi++;
}
if(bi==bs){
return times;
}
t++;
}
return -1;
}
};
思路2:
先看A、B的长度,如果A大于B,直接在A里找,不行就两个A连接在找,如果A小于B,看B是A长度的几倍多,把A重复那么多次在找,找不到在加一个A,最多加两个A,比如A=abc,B=cabca,加两个A就是B的中间包含一个完整的A,两端是A的一部分,因为可能A=abc,B=abcabc,这种刚好两次,所以这里余数为0和不为0单独分出来了,不为0可以少找一次,可能有些输入性能好一些。
class Solution {
public:
int repeatedStringMatch(string A, string B) {
int la=A.size();
int lb=B.size();
string C=A;
if(la>=lb){
for(int i=1;i<=2;++i){
if(C.find(B)!=string::npos){
return i;
}
C+=A;
}
}else{
int m=lb/la;
int n=lb%la;
for(int j=1;j<m;++j){
C+=A;
}
if(n==0){
for(int i=0;i<3;++i){
if(C.find(B)!=string::npos){
return m+i;
}
C+=A;
}
}else{
C+=A;
for(int i=1;i<=2;++i){
if(C.find(B)!=string::npos){
return m+i;
}
C+=A;
}
}
}
return -1;
};