1796. Second Largest Digit in a String

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.

Rust Solution

struct Solution;

impl Solution {
    fn second_highest(s: String) -> i32 {
        let mut set: Vec<bool> = vec![false; 10];
        for b in s.bytes() {
            if (b'0'..=b'9').contains(&b) {
                let i = (b - b'0') as usize;
                set[i] = true;
            }
        }
        let mut largest: Vec<i32> = vec![];
        for i in (0..10).rev() {
            if set[i] {
                largest.push(i as i32);
            }
        }
        if largest.len() < 2 {
            -1
        } else {
            largest[1]
        }
    }
}

#[test]
fn test() {
    let s = "dfa12321afd".to_string();
    let res = 2;
    assert_eq!(Solution::second_highest(s), res);
    let s = "abc1111".to_string();
    let res = -1;
    assert_eq!(Solution::second_highest(s), res);
}

Having problems with this solution? Click here to submit an issue on github.