3029. Minimum Time to Revert Word to Initial State I | 1660
Surprisingly easy one.
1class Solution:
2 def minimumTimeToInitialState(self, word: str, k: int) -> int:
3 # equivalent ask:
4 # the minimum x that word.startsWith(word[x*k:])
5 # "abcdefg", k = 3
6 # "defgxxx" -> "defg**a"
7 # "gxxxyyy" -> "g**abcd"
8 # "xyyyzzz" -> "abcdefg"
9
10 def startsWith(word: str, prefix: str) -> bool:
11 # "abcdefg", "abc"
12 return word[: len(prefix)] == prefix
13
14 n = len(word)
15 result = n // k + 1
16 possible_minimum = result - 1
17
18 for possible_minimum in range(result - 1, 0, -1):
19 if startsWith(word, word[possible_minimum * k :]):
20 result = possible_minimum
21
22 return result
I have realized that python string class has startswith(self) built in:
1class Solution:
2 def minimumTimeToInitialState(self, word: str, k: int) -> int:
3 n = len(word)
4 result = n // k + 1
5 possible_minimum = result - 1
6
7 for possible_minimum in range(result - 1, 0, -1):
8 if word.startswith(word[possible_minimum * k :]):
9 result = possible_minimum
10
11 return result