1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
// @Title: 最长快乐字符串 (Longest Happy String)
// @Author: 15816537946@163.com
// @Date: 2022-02-07 21:55:43
// @Runtime: 0 ms
// @Memory: 2.2 MB
// struct Solution;
impl Solution {
    pub fn longest_diverse_string(a: i32, b: i32, c: i32) -> String {
        Self::helper(a, b, c, 'a', 'b', 'c')
    }

    fn helper(a: i32, b: i32, c: i32, ch_a: char, ch_b: char, ch_c: char) -> String {
        use std::cmp::min;
        use std::iter::repeat;

        if c > b {
            return Self::helper(a, c, b, ch_a, ch_c, ch_b);
        }
        if a < b {
            return Self::helper(b, a, c, ch_b, ch_a, ch_c);
        }
        if b <= 0 {
            return repeat(ch_a).take(min(a, 2) as usize).collect::<String>();
        }

        let use_a = min(a, 2);
        let mut use_b = 1;
        if a == b {
            use_b = use_a;
        }

        repeat(ch_a)
            .take(use_a as usize)
            .chain(repeat(ch_b).take(use_b as usize))
            .chain(Self::helper(a - use_a, b - use_b, c, ch_a, ch_b, ch_c).chars())
            .collect::<String>()
    }
}