carloscn / structstudy

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

leetcode1941: Check if All Characters Have Equal Number of Occurrences #310

Open carloscn opened 1 year ago

carloscn commented 1 year ago

Description

Given a string s, return true if s is a good string, or false otherwise.

A string s is good if all the characters that appear in s have the same number of occurrences (i.e., the same frequency).

Example 1:

Input: s = "abacbc" Output: true Explanation: The characters that appear in s are 'a', 'b', and 'c'. All characters occur 2 times in s.

Example 2:

Input: s = "aaabb" Output: false Explanation: The characters that appear in s are 'a' and 'b'. 'a' occurs 3 times while 'b' occurs 2 times, which is not the same number of times.

Constraints:

1 <= s.length <= 1000 s consists of lowercase English letters.

carloscn commented 1 year ago

Analysis

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

    let mut s_vec:Vec<char> = s.chars().collect();
    let mut k_vec:Vec<char> = vec![];
    let mut count:i32;
    let mut last_count:i32 = 0;
    let mut first = true;
    s_vec.sort();
    s_vec.push(' ');

    for i in 0..s_vec.len() {
        if k_vec.is_empty() {
            k_vec.push(s_vec[i]);
            continue;
        } else {
            if k_vec[k_vec.len() - 1] != s_vec[i] {
                count = k_vec.len() as i32;
                if last_count != count {
                    if first == false {
                        return false;
                    }
                }
                last_count = count;
                first = false;
                k_vec.clear();

            }
            k_vec.push(s_vec[i]);
        }
    }

    return true;
}
carloscn commented 1 year ago

Code

https://review.gerrithub.io/c/carloscn/structstudy/+/1167702 https://github.com/carloscn/structstudy/commit/0c607157c1a3c99e47f0e21ea59a2ec5f7060628