Thursday, May 1, 2025

LeetCode 2027. Minimum Moves to Convert String

https://leetcode.com/problems/minimum-moves-to-convert-string/ 


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.
package jan21;

public class MinimumMovesForString {
public static void main(String[] args) {
String s = "XXOX";
System.out.println(minimumMoves(s));
}

public static int minimumMoves(String s) {

int i = 0, ans = 0;

while (i < s.length()) {
if (s.charAt(i) == 'X') {
i = i + 3;
ans++;
} else {
i++;
}
}
return ans;
}
}

No comments:

Post a Comment

Diagonal Traversal

 eg.  1       2       3       4 5      6       7       8 9    10    11     12 13  14   15    16 Output: 1 6 11 16 2 7 12 3 8 4  Approach:...