#1910
Medium Algorithms Remove all occurrences of a substring
String Stack Simulation
78.4% acceptance
Feb 25, 2026
2601
90
Given two strings s and part, perform the following operation on s until all occurrences of the substring part are removed:
Find the leftmost occurrence of the substring part and remove it from s.
Return s after removing all occurrences of part.
A substring is a contiguous sequence of characters in a string.
Solution
Rust
Time O(n)
Space O(1)
impl Solution {
pub fn remove_occurrences(s: String, part: String) -> String {
let mut result = String::new();
for c in s.chars() {
result.push(c);
if result.ends_with(&part) {
let new_len = result.len() - part.len();
result.truncate(new_len);
}
}
result
}
}