You are given a string s consisting of n characters which are either 'X'
or 'O'.
A move is defined as selecting threeconsecutive characters of s
and converting them to 'O'. Note that if a move is applied to the character
'O', it will stay the same.
Return _theminimum number of moves required so that all the characters of _sare converted to'O'.
Input: s ="XXOX"Output: 2Explanation: _XXO_ X -> O _OOX_ -> OOOO
We select the first 3 characters in the first move, and convert them to 'O'.Then we select the last 3 characters and convert them so that the final string contains all 'O's.
To minimize moves, whenever we see an ‘X’, we convert it and the next two characters to ‘O’ in one move, then skip ahead by three. This ensures every ‘X’ is covered with the fewest moves.
classSolution {
public:int minimumMoves(string s) {
int ans =0, i =0, n = s.size();
while (i < n) {
if (s[i] =='X') {
ans++;
i +=3;
} else {
i++;
}
}
return ans;
}
};
1
2
3
4
5
6
7
8
9
10
11
12
funcminimumMoves(sstring) int {
ans, i, n:=0, 0, len(s)
fori < n {
ifs[i] =='X' {
ans++i+=3 } else {
i++ }
}
returnans}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
classSolution {
publicintminimumMoves(String s) {
int ans = 0, i = 0, n = s.length();
while (i < n) {
if (s.charAt(i) =='X') {
ans++;
i += 3;
} else {
i++;
}
}
return ans;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
classSolution {
funminimumMoves(s: String): Int {
var ans = 0var i = 0val n = s.length
while (i < n) {
if (s[i] =='X') {
ans++ i +=3 } else {
i++ }
}
return ans
}
}
1
2
3
4
5
6
7
8
9
defminimum_moves(s: str) -> int:
ans, i, n =0, 0, len(s)
while i < n:
if s[i] =='X':
ans +=1 i +=3else:
i +=1return ans
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
impl Solution {
pubfnminimum_moves(s: String) -> i32 {
let s = s.as_bytes();
letmut ans =0;
letmut i =0;
let n = s.len();
while i < n {
if s[i] ==b'X' {
ans +=1;
i +=3;
} else {
i +=1;
}
}
ans
}
}