Minimum Moves to Convert String Problem
Description
LeetCode Problem 2027.
You are given a string s consisting of n characters which are either 'X' or 'O'.
A move is defined as selecting three consecutive 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 the minimum number of moves required so that all the characters of s are converted to 'O'.
Example 1:
Input: s = "XXX"
Output: 1
Explanation: XXX -> OOO
We select all the 3 characters and convert them in one move.
Example 2:
Input: s = "XXOX"
Output: 2
Explanation: XXOX -> OOOX -> 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.
Example 3:
Input: s = "OOOO"
Output: 0
Explanation: There are no 'X's in s to convert.
Constraints:
3 <= s.length <= 1000s[i]is either'X'or'O'.
Solution
Approach: Greedy
Scan from left to right. When we meet an 'X', it must be covered by some move, and the best move starts exactly there: it covers this 'X' and the next two characters, so count one move and jump three positions ahead. Starting any later would leave this 'X' uncovered, and starting earlier would waste cells. For any other character just step one position.
Complexity: O(n) time and O(1) extra space, where n is the length of s.
class Solution:
def minimumMoves(self, s: str) -> int:
ans = i = 0
while i < len(s):
if s[i] == "X":
ans += 1
i += 3
else:
i += 1
return ans