carloscn / structstudy

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

leetcode1805: Number of Different Integers in a String #288

Open carloscn opened 1 year ago

carloscn commented 1 year ago

Desciption

You are given a string word that consists of digits and lowercase English letters.

You will replace every non-digit character with a space. For example, "a123bc34d8ef34" will become " 123 34 8 34". Notice that you are left with some integers that are separated by at least one space: "123", "34", "8", and "34".

Return the number of different integers after performing the replacement operations on word.

Two integers are considered different if their decimal representations without any leading zeros are different.

Example 1:

Input: word = "a123bc34d8ef34" Output: 3 Explanation: The three different integers are "123", "34", and "8". Notice that "34" is only counted once.

Example 2:

Input: word = "leet1234code234" Output: 2

Example 3:

Input: word = "a1b01c001" Output: 1 Explanation: The three integers "1", "01", and "001" all represent the same integer because the leading zeros are ignored when comparing their decimal values.

Constraints:

1 <= word.length <= 1000 word consists of digits and lowercase English letters.

carloscn commented 1 year ago

Analaysis

pub fn num_different_integers(word: &str) -> i32
{
    if word.len() < 1 {
        return 0;
    }

    let wv:String = word.chars().map(|x| {
        if !x.is_numeric() {
            ' '
        } else{
            x
        }
    }).collect();

    let mut nums:Vec<i32> = vec![];
    for e in wv.split(' ') {
        if !e.is_empty() {
            nums.push(e.parse().unwrap());
        }
    }

    nums.sort();
    nums.dedup();

    return nums.len() as i32;
}
carloscn commented 1 year ago

code

https://review.gerrithub.io/c/carloscn/structstudy/+/557000 https://github.com/carloscn/structstudy/commit/f215d31bd62230aec57ccd393d3d40e9bad9969a