carloscn / structstudy

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

leetcode2423: Remove Letter To Equalize Frequency #396

Open carloscn opened 11 months ago

carloscn commented 11 months ago

Description

You are given a 0-indexed string word, consisting of lowercase English letters. You need to select one index and remove the letter at that index from word so that the frequency of every letter present in word is equal.

Return true if it is possible to remove one letter so that the frequency of all letters in word are equal, and false otherwise.

Note:

The frequency of a letter x is the number of times it occurs in the string. You must remove exactly one letter and cannot choose to do nothing.

Example 1:

Input: word = "abcc" Output: true Explanation: Select index 3 and delete it: word becomes "abc" and each character has a frequency of 1.

Example 2:

Input: word = "aazz" Output: false Explanation: We must delete a character, so either the frequency of "a" is 1 and the frequency of "z" is 2, or vice versa. It is impossible to make all present letters have equal frequency.

Constraints:

2 <= word.length <= 100 word consists of lowercase English letters only.

carloscn commented 11 months ago

Analysis

use std::collections::HashSet;

fn has_repeat(input:&Vec<char>) -> bool
{
    let mut char_set:HashSet<char> = std::collections::HashSet::new();
    for c in input {
        if !char_set.insert(*c) {
            return true;
        }
    }

    return false;
}

pub fn equal_frequency(word: &str) -> bool
{
    if word.is_empty() {
        return false;
    }

    let mut word_vec:Vec<char> = word.chars().collect();
    for i in 0..word_vec.len() {
        let removed_char: char = word_vec.remove(i);
        if !has_repeat(&word_vec) {
            return true;
        }
        word_vec.insert(i, removed_char);
    }

    return false;
}
carloscn commented 11 months ago

Code

https://review.gerrithub.io/c/carloscn/structstudy/+/1171045 https://github.com/carloscn/structstudy/commit/7eae45b915886702a151fd4dd289517fcdc3b151