Skip to main content

stack/
lib.rs

1//! # Rust :: Stack
2
3/// 1910m Remove All Occurrences of a Substring
4struct Sol1910;
5
6impl Sol1910 {
7    pub fn remove_occurrences(s: String, part: String) -> String {
8        let part = part.chars().collect::<Vec<_>>();
9
10        let mut stack = vec![];
11        for chr in s.chars() {
12            stack.push(chr);
13
14            let mut count = 0;
15            for &tchr in stack.iter().rev().take(part.len()) {
16                if part[part.len() - 1 - count] == tchr {
17                    count += 1;
18                    continue;
19                }
20                break;
21            }
22
23            if count == part.len() {
24                stack.truncate(stack.len() - part.len());
25            }
26        }
27
28        stack.iter().collect()
29    }
30}
31
32/// 3174 Clear Digits
33struct Sol3174;
34
35impl Sol3174 {
36    pub fn clear_digits(s: String) -> String {
37        let mut stack: Vec<char> = vec![];
38
39        for chr in s.chars() {
40            if chr.is_numeric() {
41                match stack.last() {
42                    Some(tchr) if tchr.is_alphabetic() => {
43                        stack.pop();
44                        continue;
45                    }
46                    _ => (),
47                }
48            }
49
50            stack.push(chr);
51        }
52
53        stack.iter().collect()
54    }
55}
56
57#[cfg(test)]
58mod tests {
59    use super::*;
60
61    #[test]
62    fn test_1910() {
63        assert_eq!(
64            Sol1910::remove_occurrences("daabcbaabcbc".to_string(), "abc".to_string()),
65            "dab".to_string()
66        );
67        assert_eq!(
68            Sol1910::remove_occurrences("axxxxyyyyb".to_string(), "xy".to_string()),
69            "ab".to_string()
70        );
71    }
72
73    #[test]
74    fn test_3174() {
75        assert_eq!(Sol3174::clear_digits("abc".to_string()), "abc".to_string());
76        assert_eq!(Sol3174::clear_digits("cb34".to_string()), "".to_string());
77    }
78}