Skip to content

Commit ba202e3

Browse files
committed
Add solution #466
1 parent 66142d3 commit ba202e3

File tree

2 files changed

+57
-0
lines changed

2 files changed

+57
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -373,6 +373,7 @@
373373
462|[Minimum Moves to Equal Array Elements II](./0462-minimum-moves-to-equal-array-elements-ii.js)|Medium|
374374
463|[Island Perimeter](./0463-island-perimeter.js)|Medium|
375375
464|[Can I Win](./0464-can-i-win.js)|Medium|
376+
466|[Count The Repetitions](./0466-count-the-repetitions.js)|Hard|
376377
472|[Concatenated Words](./0472-concatenated-words.js)|Hard|
377378
476|[Number Complement](./0476-number-complement.js)|Easy|
378379
482|[License Key Formatting](./0482-license-key-formatting.js)|Easy|
Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
/**
2+
* 466. Count The Repetitions
3+
* https://leetcode.com/problems/count-the-repetitions/
4+
* Difficulty: Hard
5+
*
6+
* We define str = [s, n] as the string str which consists of the string s concatenated n times.
7+
*
8+
* - For example, str == ["abc", 3] =="abcabcabc".
9+
*
10+
* We define that string s1 can be obtained from string s2 if we can remove some characters from
11+
* s2 such that it becomes s1.
12+
*
13+
* - For example, s1 = "abc" can be obtained from s2 = "abdbec" based on our definition by
14+
* removing the bolded underlined characters.
15+
*
16+
* You are given two strings s1 and s2 and two integers n1 and n2. You have the two strings
17+
* str1 = [s1, n1] and str2 = [s2, n2].
18+
*
19+
* Return the maximum integer m such that str = [str2, m] can be obtained from str1.
20+
*/
21+
22+
/**
23+
* @param {string} s1
24+
* @param {number} n1
25+
* @param {string} s2
26+
* @param {number} n2
27+
* @return {number}
28+
*/
29+
var getMaxRepetitions = function(s1, n1, s2, n2) {
30+
const pattern = {};
31+
let s2Count = 0;
32+
let s2Index = 0;
33+
34+
for (let i = 0; i < n1; i++) {
35+
for (let j = 0; j < s1.length; j++) {
36+
if (s1[j] === s2[s2Index]) {
37+
s2Index++;
38+
if (s2Index === s2.length) {
39+
s2Index = 0;
40+
s2Count++;
41+
}
42+
}
43+
}
44+
45+
if (pattern[s2Index]) {
46+
const [prevIndex, prevCount] = pattern[s2Index];
47+
const remainingCycles = Math.floor((n1 - i - 1) / (i - prevIndex));
48+
i += remainingCycles * (i - prevIndex);
49+
s2Count += remainingCycles * (s2Count - prevCount);
50+
} else {
51+
pattern[s2Index] = [i, s2Count];
52+
}
53+
}
54+
55+
return Math.floor(s2Count / n2);
56+
};

0 commit comments

Comments
 (0)