Leetcode 2027. Minimum Moves to Convert String
You are given a string s
consisting of n
characters where each character is either 'X'
or '.'
. A move consists of changing three consecutive characters from 'X'
to '.'
. Your task is to return the minimum number of moves required to convert the string such that there are no characters 'X'
in the string.
Before diving into the solution, let’s clarify a few points:
s
?'X'
: Are the 'X'
characters always contiguous or can they be scattered throughout the string?'.'
?'X'
: Can the moves overlap? Would changing three X
s affect adjacent characters?We will assume:
s
can be of any length up to a reasonably large constraint.'X'
characters can appear anywhere intermittently and the moves do not overlap; each move affects a distinct set of 3 characters.'X'
, we will make a move that changes the current and the next two characters to '.'
.Here is the C++ code to solve the problem:
#include <iostream>
#include <string>
int minimumMoves(std::string s) {
int n = s.size();
int moves = 0;
for (int i = 0; i < n; ++i) {
if (s[i] == 'X') {
// We found an 'X', hence we make a move to turn this and next two characters into '.'
moves++;
// Skip the next two characters since this move will already convert them
i += 2;
}
}
return moves;
}
int main() {
std::string s = "XX.XX..XXX";
std::cout << "Minimum moves to convert the string: " << minimumMoves(s) << std::endl;
return 0;
}
moves = 0
and iterate through each character of s
.moves
counter.'.'
by this move.moves
variable will contain the minimal number of moves required.n
is the length of the string. This is because we iterate through the string once.This approach ensures that we efficiently find the minimal number of moves required to convert all 'X'
characters in the string to '.'
.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?