Algorithm: Leetcode Contest 383
3029. Minimum Time to Revert Word to Initial State I
You are given a 0-indexed string word
and an integer k
.
At every second, you must perform the following operations:
- Remove the first
k
characters ofword
. - Add any
k
characters to the end ofword
.
Note that you do not necessarily need to add the same characters that you removed. However, you must perform both operations at every second.
Return the minimum time greater than zero required for word
to revert to its initial state.
Solution
class Solution {
public int minimumTimeToInitialState(String word, int k) {
String copy = new String(word);
int count = 0;
do {
word = word.substring(k) + "*".repeat(k);
count++;
} while (!isStringEqual(copy, word));
return count;
}
private boolean isStringEqual(String str1, String str2) {
if (str1.length() != str2.length()) {
return false;
}
for (int i = 0; i < str1.length(); i++) {
if (str2.charAt(i) == '*') {
continue;
} else if (str1.charAt(i) != str2.charAt(i)) {
return false;
}
}
return true;
}
}
Retro
- the adoption of “*” to represent omni character is very inspiring
- the API of string manipulation
- the usage of substring, passing K represent K to end
- replicate a character : “*“.repeat(K)