Input: word ="abacaba", k =3Output: 2Explanation: At the 1st second, we remove characters "aba" from the prefix of word, and add characters "bac" to the end of word. Thus, word becomes equal to "cababac".At the 2nd second, we remove characters "cab" from the prefix of word, and add "aba" to the end of word. Thus, word becomes equal to "abacaba" and reverts to its initial state.It can be shown that 2 seconds is the minimum time greater than zero required for word to revert to its initial state.
Input: word ="abacaba", k =4Output: 1Explanation: At the 1st second, we remove characters "abac" from the prefix of word, and add characters "caba" to the end of word. Thus, word becomes equal to "abacaba" and reverts to its initial state.It can be shown that 1 second is the minimum time greater than zero required for word to revert to its initial state.
Input: word ="abcbabcd", k =2Output: 4Explanation: At every second, we will remove the first 2 characters of word, and add the same characters to the end of word.After 4 seconds, word becomes equal to "abcbabcd" and reverts to its initial state.It can be shown that 4 seconds is the minimum time greater than zero required for word to revert to its initial state.
Since the word length is small (<= 50), we can simulate the process of removing the first k characters and appending them to the end, until the word returns to its initial state. The minimum time is the first t > 0 when the word matches the original.
classSolution {
public:int minTimeToRevert(string word, int k) {
string orig = word;
int t =0, n = word.size();
do {
t++;
string pre = word.substr(0, k);
word = word.substr(k) + pre;
} while (word != orig);
return t;
}
};
1
2
3
4
5
6
7
8
9
10
11
12
funcminTimeToRevert(wordstring, kint) int {
orig:=wordt:=0for {
t++pre:=word[:k]
word = word[k:] +preifword==orig {
returnt }
}
}
1
2
3
4
5
6
7
8
9
10
11
12
classSolution {
publicintminTimeToRevert(String word, int k) {
String orig = word;
int t = 0;
do {
t++;
String pre = word.substring(0, k);
word = word.substring(k) + pre;
} while (!word.equals(orig));
return t;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
classSolution {
funminTimeToRevert(word: String, k: Int): Int {
val orig = word
var w = word
var t = 0do {
t++val pre = w.substring(0, k)
w = w.substring(k) + pre
} while (w != orig)
return t
}
}
1
2
3
4
5
6
7
8
9
10
classSolution:
defminTimeToRevert(self, word: str, k: int) -> int:
orig: str = word
t: int =0whileTrue:
t +=1 pre: str = word[:k]
word = word[k:] + pre
if word == orig:
return t
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
impl Solution {
pubfnmin_time_to_revert(word: String, k: i32) -> i32 {
let orig = word.clone();
letmut w = word;
letmut t =0;
let k = k asusize;
loop {
t +=1;
let pre = w[..k].to_string();
w = w[k..].to_string() +⪯
if w == orig {
return t;
}
}
}
}