Problem overview
Version 3 mirrors tr -d. tr_delete(lines, chars) removes from every line each character that appears in chars, then returns the lines joined by \n. The string chars is non-empty ASCII, its characters are literal, and case matters. A line can become empty after deletion, and it then stays in the output as an empty line. The previous version translated characters through a map. This one only needs to know whether a character is in a group.
For ["banana", "apple"] with "aeiou", the vowels vanish and the result is "bnn\nppl".
Approach
For each character of each line, ask one question: is it one of the characters to delete? A HashSet answers that in constant time on average. Build the set once from chars, then copy every character that is not in the set into the output.
This solution builds one big String directly instead of collecting lines in a vector. That changes how the newlines work: there is no join, so the loop itself pushes a '\n' before every line except the first. A newline between two lines, and none after the last, is exactly what join would have produced.
Following "banana" with the set of vowels: b isn't in the set and is kept, a is in it and is skipped, n is kept, and so on, which leaves "bnn". In "apple", the a and the final e are skipped and "ppl" remains. The newline pushed between the two lines is not affected by any deletion, because it is added by the line loop and not by the character loop, and it is never tested against the set.
Step by step
- Create
set, an emptyHashSet, withlet mut. - Loop over the characters of
charswithchars.chars(). The function parameter and its method are both namedchars, which is legal because one is a variable and the other a method. - Insert each character into the set. A set stores each value once, so repeats in
charsare harmless. - Create
result, an emptyString. Everything is appended to its end. - Loop over the line positions with
for i in 0..lines.len(). - Check
i > 0. The first line needs no newline before it. - Push
'\n'inside that check. A single character goes in single quotes. - Loop over the characters of
lines[i]with.chars(). - Test
!set.contains(&ch), which is true for characters to keep. - Push the character onto
resultinside that test. Characters in the set are skipped, which deletes them. - Return
resultafter both loops.
The solution in Rust
impl Solution {
fn tr_delete(lines: Vec<String>, chars: String) -> String {
let mut set = HashSet::new();
for ch in chars.chars() {
set.insert(ch);
}
let mut result = String::new();
for i in 0..lines.len() {
if i > 0 {
result.push('\n');
}
for ch in lines[i].chars() {
if !set.contains(&ch) {
result.push(ch);
}
}
}
return result;
}
}
Rust details:
HashSetand its type. It lives instd::collections(use std::collections::HashSet;in a standalone program). The element type,char, is inferred from theinsertcall.containstakes a reference. That is why the call isset.contains(&ch), notset.contains(ch).pushagainstpush_str.String::pushappends onechar, written in single quotes, such as'\n'.push_strappends a whole&str, written in double quotes.- Indexing
lines[i]. This borrows the line for the loop and doesn't move it out of the vector. - Characters.
chars()yieldscharvalues, so the code compares whole characters and never needs to index into a string by byte.
The same idea can be written with an iterator. line.chars().filter(|c| !set.contains(c)).collect::<String>() keeps the characters that are not in the set and gathers them into a new String; on "banana" with the vowels set it gives "bnn". The lesson uses explicit loops instead, which makes each step visible. In the filter closure, c is already a reference to the character, so contains takes it without an extra &.
Complexity
Time: O(C + L), where C is the length of chars and L the total length of the lines: one insertion per member, then one average-constant-time lookup per line character. Space: O(C + L) for the set and the result.
Edge cases and common mistakes
- A line that becomes empty.
["aaa", "bab", "x"]with"a"gives"\nbb\nx". The first line is now empty, but its newline separator is still there. - Case.
["Aa"]with"a"gives"A". Only the lowercase letter matches. - Empty list. The loop never runs and the result is
"". - An empty line among others.
["", "q"]gives"\nq", because the newline before the second line is pushed regardless. - Repeated characters in
chars.["abc"]with"aab"gives"c". The set just storesaonce. - Newline placement. Pushing a newline after every line, or when
iis the last position, would give a trailing newline the tests don't expect. - Deleting the newline too. The separators are written outside the inner loop. If the delete set contained a newline character, it would still not remove them, because the set only filters the characters of the lines.
- Forgetting the
!. Without it, the code keeps only the characters that should be deleted.
Testing
["banana", "apple"]with"aeiou"gives"bnn\nppl".["aaa", "bab", "x"]with"a"gives"\nbb\nx".["Aa"]with"a"gives"A".["", "q"]with"a"gives"\nq".[]with"a"gives"".
