LeetCode 767. Reorganize String

Problem Statement


use std::collections::{BinaryHeap, HashMap};

impl Solution {
pub fn reorganize_string(s: String) -> String {
let mut map: HashMap<char, i32> = HashMap::new();
let mut heap: BinaryHeap<(i32, char)> = BinaryHeap::new();
for c in s.chars() {
let count = map.entry(c).or_insert(0);
*count += 1;
}
let mut ans = "".to_string();
for (k, v) in &map {
if *v > ((s.len() + 1) / 2) as i32 {
return ans;
}
heap.push((*v, *k));
}
while heap.len() >= 2 {
let (mut t1, mut t2) = (heap.pop().unwrap(), heap.pop().unwrap());
ans.push(t1.1); ans.push(t2.1);
t1.0 -= 1; t2.0 -= 1;
if t1.0 != 0 {
heap.push(t1);
}
if t2.0 != 0 {
heap.push(t2);
}
}

if !heap.is_empty() {
let t = heap.pop().unwrap();
ans.push(t.1);
}
return ans;
}
}