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:
trDelete(lines, chars)
Example:
Input: lines = ["banana", "apple"], chars = "aeiou" Output: "bnn\nppl" When printed: bnn ppl
Build a
Set from chars (passing a string to the Set constructor iterates char-by-char). For each line, walk char-by-char and keep characters NOT in the set.
let set = new Set(chars);
// per char: if (!set.has(ch)) out += ch;
The full solution:
class Solution {
trDelete(lines, chars) {
let set = new Set(chars);
let result = [];
for (let i = 0; i < lines.length; i++) {
let out = "";
for (let j = 0; j < lines[i].length; j++) {
if (!set.has(lines[i][j])) {
out += lines[i][j];
}
}
result.push(out);
}
return result.join("\n");
}
}
Free plan: 30 tutor messages. Premium is unlimited.
Saved
Ctrl + Enter to check
