Skip to main content

rustgym/leetcode/
_767_reorganize_string.rs

1struct Solution;
2use std::collections::HashMap;
3use std::collections::VecDeque;
4
5impl Solution {
6    fn reorganize_string(s: String) -> String {
7        let n = s.len();
8        let mut s: Vec<char> = s.chars().collect();
9        let mut hm: HashMap<char, usize> = HashMap::new();
10        for &c in s.iter() {
11            *hm.entry(c).or_default() += 1;
12            if hm[&c] > (n + 1) / 2 {
13                return "".to_string();
14            }
15        }
16        s.sort_unstable_by_key(|c| (hm[&c], *c));
17        s[0..n / 2].reverse();
18        let mut queue: VecDeque<char> = VecDeque::new();
19        for c in s {
20            queue.push_back(c);
21        }
22        let mut i = 0;
23        let mut res = "".to_string();
24        while !queue.is_empty() {
25            if i % 2 == 0 {
26                res.push(queue.pop_back().unwrap());
27            } else {
28                res.push(queue.pop_front().unwrap());
29            }
30            i += 1;
31        }
32        res
33    }
34}
35
36#[test]
37fn test() {
38    let s = "aab".to_string();
39    let res = "aba".to_string();
40    assert_eq!(Solution::reorganize_string(s), res);
41    let s = "aaab".to_string();
42    let res = "".to_string();
43    assert_eq!(Solution::reorganize_string(s), res);
44}