Build a version of the Unix tr -d command. Given a list of lines and a string chars, remove every character that appears in chars from each line, then return the lines joined by newline characters (\n).
Notes: chars is a non-empty ASCII string whose characters are taken literally (no ranges). Upper and lower case are different characters. A line can become empty after deleting, and then it stays as an empty line in the output.
Function signature:
fn tr_delete(lines: Vec<String>, chars: String) -> String
Example:
Input: lines = ["banana", "apple"], chars = "aeiou" Output: "bnn\nppl" When printed: bnn ppl
Put each character of
chars into a HashSet<char> for O(1) lookup. Walk every line and append characters that are NOT in the set.
The full solution:
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;
}
}
Free plan: 30 tutor messages. Premium is unlimited.
Saved
Ctrl + Enter to check
