思路: 2是个很关键的数字,可以表示有后一半开头的情况。直接上代码吧:
class Solution {
public:
int repeatedStringMatch(string a, string b) {
int len1 = a.size(), len2 = b.size();
string str1 = a, str2 = a + a, str3 = a + a + a;
int ans = 0;
if (len2 < 2 * len1) {
if (str1.find(b) != -1) return 1;
else if (str2.find(b) != -1) return 2;
else if (str3.find(b) != -1) return 3;
else return -1;
}else {
int st = b.find(a), s = st;
if (st == -1) return -1;
while (st + len1 - 1 < len2) {
if (b.substr(st, len1) == a) {
st += len1;
ans++;
}else return -1;
}
if (st < len2 && (b.substr(st, len2 - st) == a.substr(0, len2 - st))) ans++;
if (st < len2 && (b.substr(st, len2 - st) != a.substr(0, len2 - st))) return -1;
if (s > 0 && (b.substr(0, s) == a.substr(len1 - s, s))) ans++;
if (s > 0 && (b.substr(0, s) != a.substr(len1 - s, s))) return -1;
}
return ans;
}
};
易错点 1:必须要加: else if (str3.find(b) != -1) return 3; 因为b可能是a前面加一点,后面加一点这种情况
|