carloscn / structstudy

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

leetcode1796: Second Largest Digit in a String #284

Open carloscn opened 1 year ago

carloscn commented 1 year ago

Description

Given an alphanumeric string s, return the second largest numerical digit that appears in s, or -1 if it does not exist.

An alphanumeric string is a string consisting of lowercase English letters and digits.

Example 1:

Input: s = "dfa12321afd" Output: 2 Explanation: The digits that appear in s are [1, 2, 3]. The second largest digit is 2.

Example 2:

Input: s = "abc1111" Output: -1 Explanation: The digits that appear in s are [1]. There is no second largest digit.

Constraints:

1 <= s.length <= 500 s consists of only lowercase English letters and/or digits.

carloscn commented 1 year ago

Analysis

pub fn second_highest(s: &str) -> i32
{
    if s.is_empty() {
        return 0;
    }

    let mut s_vec:Vec<char> = s.chars()
                               .filter(|&x| x.is_numeric())
                               .collect();

    s_vec.sort();
    s_vec.dedup();

    if s_vec.len() < 2 {
        return -1;
    } else {
        return ((s_vec[1] as u8) - ('0' as u8)) as i32;
    }
}
carloscn commented 1 year ago

code

https://review.gerrithub.io/c/carloscn/structstudy/+/556923 https://github.com/carloscn/structstudy/commit/8edeb08aa5475790dcc9bdf749f28bb7a863ea17