686. Repeated String Match

时间:2022-08-23 01:23:22

方法一、算是暴力解法吧,拼一段找一下

 static int wing=[]()
{
std::ios::sync_with_stdio(false);
cin.tie(NULL);
return ;
}(); class Solution
{
public:
int repeatedStringMatch(string A, string B)
{
string as=A;
int count=B.size()/A.size()+;
for(int i=;i<count;i++,as+=A)
{
if(as.find(B)!=string::npos)
return i;
}
return -;
}
};

方法二、稍微有点技术含量了,运行速度快些

 static int wing=[]()
{
std::ios::sync_with_stdio(false);
cin.tie(NULL);
return ;
}(); class Solution
{
public:
int repeatedStringMatch(string A, string B)
{
string tmp=A+A;
size_t pos=tmp.find(B.substr(,A.size()));
if(pos==string::npos)
return -;
int count=;
size_t i=;
while(i<B.size())
{
if(pos==A.size())
{
pos=;
++count;
}
if(A[pos++]!=B[i++])
return -;
}
return count;
}
};

先把两个A拼起来成为tmp,在tmp中找B的前面一截,若没找到,则B必然不能成为A拼接序列的子串

若找到了,再进行下面的判定,一个字符一个字符来,扫到A末尾则回到A首部并增加计数器,直到找到B的所有元素