LeetCode 1209. Remove All Adjacent Duplicates in String II

Problem Statement


impl Solution {
pub fn remove_duplicates(s: String, k: i32) -> String {
let mut stack = vec![(0, '#')];
let mut ans = "".to_string();
for c in s.chars() {
let index = stack.len() - 1;
if stack[index].1 != c {
stack.push((1, c));
} else if stack[index].0 == k - 1 {
stack.pop();
} else {
let mut val = stack[index];
val.0 += 1;
stack[index] = val;
}
}

for item in stack {
ans.push_str(&(0..item.0 as usize).map(|_| item.1).collect::<String>());
}
return ans;
}
}