carloscn / structstudy

Leetcode daily trainning by using C/C++/RUST programming.
4 stars 1 forks source link

leetcode2027: Minimum Moves to Convert String #325

Open carloscn opened 1 year ago

carloscn commented 1 year ago

Description

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 <= 1000 s[i] is either 'X' or 'O'.

carloscn commented 1 year ago

Analysis

pub fn minimum_moves(s: &str) -> i32
{
    let mut ret:i32 = 0;

    if s.len() < 1 {
        return ret;
    }

    let s_v:Vec<char> = s.chars().collect();
    let mut count:usize = 0;

    for i in 0..s_v.len() {
        if s_v[i] != 'X' {
            count = 0;
            continue;
        } else {
            if count == 0 {
                ret += 1;
            }
            count += 1;
        }
    }

    return ret;
}
carloscn commented 1 year ago

Code

https://review.gerrithub.io/c/carloscn/structstudy/+/1168404 https://github.com/carloscn/structstudy/commit/20064b291743959c1a9ae085c18168a68c1cb8df