Skip to content

Commit fd296d1

Browse files
authored
Create minimum-time-to-revert-word-to-initial-state-i.cpp
1 parent 17e39cf commit fd296d1

File tree

1 file changed

+64
-0
lines changed

1 file changed

+64
-0
lines changed
Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
// Time: O(n)
2+
// Space: O(n)
3+
4+
// z-function
5+
class Solution {
6+
public:
7+
int minimumTimeToInitialState(string word, int k) {
8+
const auto& ceil_divide = [](int a, int b) {
9+
return (a + b - 1) / b;
10+
};
11+
12+
// Template: https://cp-algorithms.com/string/z-function.html
13+
const auto& z_function = [](const string& s) { // Time: O(n), Space: O(n)
14+
vector<int> z(size(s));
15+
for (int i = 1, l = 0, r = 0; i < size(z); ++i) {
16+
if (i <= r) {
17+
z[i] = min(r - i + 1, z[i - l]);
18+
}
19+
while (i + z[i] < size(z) && s[z[i]] == s[i + z[i]]) {
20+
++z[i];
21+
}
22+
if (i + z[i] - 1 > r) {
23+
l = i, r = i + z[i] - 1;
24+
}
25+
}
26+
return z;
27+
};
28+
29+
const auto& z = z_function(word);
30+
for (int i = k; i < size(word); i += k) {
31+
if (z[i] == size(word) - i) {
32+
return i / k;
33+
}
34+
}
35+
return ceil_divide(size(word), k);
36+
}
37+
};
38+
39+
// Time: O(n^2)
40+
// Space: O(1)
41+
// brute force
42+
class Solution2 {
43+
public:
44+
int minimumTimeToInitialState(string word, int k) {
45+
const auto& ceil_divide = [](int a, int b) {
46+
return (a + b - 1) / b;
47+
};
48+
const auto& check = [&](int i) {
49+
for (int j = 0; i + j < size(word); ++j) {
50+
if (word[i + j] != word[j]) {
51+
return false;
52+
}
53+
}
54+
return true;
55+
};
56+
57+
for (int i = k; i < size(word); i += k) {
58+
if (check(i)) {
59+
return i / k;
60+
}
61+
}
62+
return ceil_divide(size(word), k);
63+
}
64+
};

0 commit comments

Comments
 (0)