carloscn / structstudy

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

leetcode2124: Check if All A's Appears Before All B's #343

Open carloscn opened 1 year ago

carloscn commented 1 year ago

Description

Given a string s consisting of only the characters 'a' and 'b', return true if every 'a' appears before every 'b' in the string. Otherwise, return false.

Example 1:

Input: s = "aaabbb" Output: true Explanation: The 'a's are at indices 0, 1, and 2, while the 'b's are at indices 3, 4, and 5. Hence, every 'a' appears before every 'b' and we return true.

Example 2:

Input: s = "abab" Output: false Explanation: There is an 'a' at index 2 and a 'b' at index 1. Hence, not every 'a' appears before every 'b' and we return false.

Example 3:

Input: s = "bbb" Output: true Explanation: There are no 'a's, hence, every 'a' appears before every 'b' and we return true.

Constraints:

1 <= s.length <= 100 s[i] is either 'a' or 'b'.

carloscn commented 1 year ago

Analysis

pub fn check_string(s: &str) -> bool
{
    if s.len() < 1 {
        return false;
    }

    let s_vec:Vec<char> = s.chars().collect();
    let mut a_flag = false;

    for i in 0..s_vec.len() {
        let e = s_vec[s_vec.len() - i - 1];
        if e == 'a' {
            a_flag = true;
        } else if e == 'b' {
            if a_flag == true {
                return false;
            }
        } else {
            return false;
        }
    }

    return true;
}
carloscn commented 1 year ago

Code

https://review.gerrithub.io/c/carloscn/structstudy/+/1168851 https://github.com/carloscn/structstudy/commit/840b6fe3b0e9ffd9b1e947cafe2a7cd13be9c0f5