rustgym/leetcode/
_1209_remove_all_adjacent_duplicates_in_string_2.rs1struct Solution;
2
3impl Solution {
4 fn remove_duplicates(s: String, k: i32) -> String {
5 let mut stack: Vec<(char, usize)> = vec![];
6 for c in s.chars() {
7 if let Some(top) = stack.pop() {
8 if top.0 != c {
9 stack.push(top);
10 stack.push((c, 1));
11 } else {
12 if (top.1 + 1) != k as usize {
13 stack.push((c, top.1 + 1));
14 }
15 }
16 } else {
17 stack.push((c, 1));
18 }
19 }
20 let mut res = "".to_string();
21 for p in stack {
22 for _ in 0..p.1 {
23 res.push(p.0);
24 }
25 }
26 res
27 }
28}
29
30#[test]
31fn test() {
32 let s = "abcd".to_string();
33 let k = 2;
34 let res = "abcd".to_string();
35 assert_eq!(Solution::remove_duplicates(s, k), res);
36 let s = "deeedbbcccbdaa".to_string();
37 let k = 3;
38 let res = "aa".to_string();
39 assert_eq!(Solution::remove_duplicates(s, k), res);
40 let s = "pbbcggttciiippooaais".to_string();
41 let k = 2;
42 let res = "ps".to_string();
43 assert_eq!(Solution::remove_duplicates(s, k), res);
44}