题目链接


Python3
方法: 找循环节(m个s1对应n个s2) ⟮O(∣s1∣×∣s2∣)、O(∣s2∣)⟯
官方题解

class Solution:
def getMaxRepetitions(self, s1: str, n1: int, s2: str, n2: int) -> int:
index, s1cnt, s2cnt = 0, 0, 0
recall = dict()
while True:
s1cnt += 1
for ch in s1:
if ch == s2[index]:
index += 1
if index == len(s2):
s2cnt, index = s2cnt + 1, 0
if s1cnt == n1:
return s2cnt // n2
if index in recall:
s1cnt_prime, s2cnt_prime = recall[index]
pre_loop = (s1cnt_prime, s2cnt_prime)
in_loop = (s1cnt - s1cnt_prime, s2cnt - s2cnt_prime)
break
else:
recall[index] = (s1cnt, s2cnt)
res = pre_loop[1] + (n1 - pre_loop[0]) // in_loop[0] * in_loop[1]
rest = (n1 - pre_loop[0]) % in_loop[0]
for i in range(rest):
for ch in s1:
if ch == s2[index]:
index += 1
if index == len(s2):
res, index = res + 1, 0
return res // n2

C++
方法: 找循环节(m个s1对应n个s2) ⟮O(∣s1∣×∣s2∣)、O(∣s2∣)⟯
class Solution {
public:
int getMaxRepetitions(string s1, int n1, string s2, int n2) {
int s1cnt = 0, s2cnt = 0, index = 0;
unordered_map<int, pair<int, int>> matched;
pair<int, int>pre_loop, in_loop;
while (true){
++s1cnt;
for (char ch : s1){
if (ch == s2[index]){
index += 1;
if (index == s2.size()){
++s2cnt;
index = 0;
}
}
}
if (s1cnt == n1){
return s2cnt / n2;
}
if (matched.count(index)){
auto [s1cnt_prime, s2cnt_prime] = matched[index];
pre_loop = {s1cnt_prime, s2cnt_prime};
in_loop = {s1cnt - s1cnt_prime, s2cnt - s2cnt_prime};
break;
}else{
matched[index] = {s1cnt, s2cnt};
}
}
int res = pre_loop.second + (n1 - pre_loop.first) / in_loop.first * in_loop.second;
int rest = (n1 - pre_loop.first) % in_loop.first;
for (int i = 0; i < rest; ++i){
for (char ch : s1){
if (ch == s2[index]){
++index;
if (index == s2.size()){
++res;
index = 0;
}
}
}
}
return res / n2;
}
};