2264. Largest 3-Same-Digit Number in String Easy
1/**
2 * [2264] Largest 3-Same-Digit Number in String
3 *
4 * You are given a string num representing a large integer. An integer is good if it meets the following conditions:
5 *
6 * It is a substring of num with length 3.
7 * It consists of only one unique digit.
8 *
9 * Return the maximum good integer as a string or an empty string "" if no such integer exists.
10 * Note:
11 *
12 * A substring is a contiguous sequence of characters within a string.
13 * There may be leading zeroes in num or a good integer.
14 *
15 *
16 * Example 1:
17 *
18 * Input: num = "6<u>777</u>133339"
19 * Output: "777"
20 * Explanation: There are two distinct good integers: "777" and "333".
21 * "777" is the largest, so we return "777".
22 *
23 * Example 2:
24 *
25 * Input: num = "23<u>000</u>19"
26 * Output: "000"
27 * Explanation: "000" is the only good integer.
28 *
29 * Example 3:
30 *
31 * Input: num = "42352338"
32 * Output: ""
33 * Explanation: No substring of length 3 consists of only one unique digit. Therefore, there are no good integers.
34 *
35 *
36 * Constraints:
37 *
38 * 3 <= num.length <= 1000
39 * num only consists of digits.
40 *
41 */
42pub struct Solution {}
43
44// problem: https://leetcode.com/problems/largest-3-same-digit-number-in-string/
45// discuss: https://leetcode.com/problems/largest-3-same-digit-number-in-string/discuss/?currentPage=1&orderBy=most_votes&query=
46
47// submission codes start here
48
49impl Solution {
50 pub fn largest_good_integer(num: String) -> String {
51 let chs: Vec<char> = num.chars().collect();
52 let mut max = 0;
53 let mut result: String = String::from("");
54 for i in 1..chs.len() - 1 {
55 if chs[i - 1] == chs[i] && chs[i] == chs[i + 1] {
56 let t = num[i - 1..i + 2].to_string().parse::<i32>().unwrap();
57 if t >= max {
58 max = t;
59 result = num[i - 1..i + 2].into();
60 }
61 }
62 }
63 result
64 }
65}
66
67// submission codes end
68
69#[cfg(test)]
70mod tests {
71 use super::*;
72
73 #[test]
74 fn test_2264_1() {
75 assert_eq!(Solution::largest_good_integer(String::from("222")), "222");
76 assert_eq!(Solution::largest_good_integer(String::from("42352338")), "");
77 assert_eq!(Solution::largest_good_integer(String::from("23<u>000</u>19")), "000");
78 assert_eq!(Solution::largest_good_integer(String::from("6<u>777</u>133339")), "777");
79 assert_eq!(Solution::largest_good_integer(String::from("666<u>777</u>133339")), "777");
80 }
81}
82
Back
© 2025 bowen.ge All Rights Reserved.