解题思路:
一道看起来很简单的题目,解题的关键在于分析。首先考虑两种情况,b的长度比a短,或者b的长度比a长,比a短还能是a的子串,只能说b是a的子串或者是两个a连接的中间部分,如果b的长度比a的长度长,a首先得叠加到至少大于等于b的长度,此时b也可能是当前叠加得到的两个a连接的中间部分。所以,综上所述,不管叠加几次,我们都能知道最大的叠加次数是多少,既然这样每次从1开始一直遍历到最大叠加次数,查看中间是否有b,有则返回次数无则继续。最终没找到返回-1,代码如下:
class Solution {
public:
int repeatedStringMatch(string a, string b) {
string temp = a;
// 翻转次数
int count = 1;
int lenA = a.size(), lenB = b.size();
// 最多翻转次数
int maxCount = lenB / lenA;
while(count <= maxCount + 2) {
if(temp.find(b) != string::npos) {
return count;
}
temp += a;
count ++;
}
return -1;
}
};
时间复杂度:O(n/m)
空间复杂度:O(1)