Skip to content

Commit 903b4aa

Browse files
committed
1796. Second Largest Digit in a String: AC
1 parent 609a2f4 commit 903b4aa

File tree

2 files changed

+74
-0
lines changed

2 files changed

+74
-0
lines changed

src/solution/mod.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1352,3 +1352,4 @@ mod s1790_check_if_one_string_swap_can_make_strings_equal;
13521352
mod s1791_find_center_of_star_graph;
13531353
mod s1792_maximum_average_pass_ratio;
13541354
mod s1793_maximum_score_of_a_good_subarray;
1355+
mod s1796_second_largest_digit_in_a_string;
Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
/**
2+
* [1796] Second Largest Digit in a String
3+
*
4+
* Given an alphanumeric string s, return the second largest numerical digit that appears in s, or -1 if it does not exist.
5+
* An alphanumeric string is a string consisting of lowercase English letters and digits.
6+
*
7+
* Example 1:
8+
*
9+
* Input: s = "dfa12321afd"
10+
* Output: 2
11+
* Explanation: The digits that appear in s are [1, 2, 3]. The second largest digit is 2.
12+
*
13+
* Example 2:
14+
*
15+
* Input: s = "abc1111"
16+
* Output: -1
17+
* Explanation: The digits that appear in s are [1]. There is no second largest digit.
18+
*
19+
*
20+
* Constraints:
21+
*
22+
* 1 <= s.length <= 500
23+
* s consists of only lowercase English letters and digits.
24+
*
25+
*/
26+
pub struct Solution {}
27+
28+
// problem: https://leetcode.com/problems/second-largest-digit-in-a-string/
29+
// discuss: https://leetcode.com/problems/second-largest-digit-in-a-string/discuss/?currentPage=1&orderBy=most_votes&query=
30+
31+
// submission codes start here
32+
33+
impl Solution {
34+
pub fn second_highest(s: String) -> i32 {
35+
s.bytes()
36+
.filter_map(|b| b.is_ascii_digit().then_some((b - b'0') as i32))
37+
.fold((-1, -1), |(p, u), d| {
38+
if d > u {
39+
(u, d)
40+
} else if d > p && d < u {
41+
(d, u)
42+
} else {
43+
(p, u)
44+
}
45+
})
46+
.0
47+
}
48+
}
49+
50+
// submission codes end
51+
52+
#[cfg(test)]
53+
mod tests {
54+
use super::*;
55+
56+
#[test]
57+
fn test_1796_example_1() {
58+
let s = "dfa12321afd".to_string();
59+
60+
let result = 2;
61+
62+
assert_eq!(Solution::second_highest(s), result);
63+
}
64+
65+
#[test]
66+
fn test_1796_example_2() {
67+
let s = "abc1111".to_string();
68+
69+
let result = -1;
70+
71+
assert_eq!(Solution::second_highest(s), result);
72+
}
73+
}

0 commit comments

Comments
 (0)