Build a version of the Unix tr -s command. Given a list of lines and a string chars, collapse consecutive runs of any character that appears in chars to a single occurrence. Other characters are unchanged. Return the lines joined by newline characters (\n).
Notes: chars is a non-empty ASCII string whose characters are taken literally (no ranges). Only runs of the same character from chars are collapsed; all other characters, and runs of characters not in chars, stay as they are. Upper and lower case are different characters. Lines may be empty.
Function signature:
trSqueeze(lines, chars)
Example:
Input: lines = ["aaabbb", "abaa"], chars = "a" Output: "abbb\naba" When printed: abbb aba
Build a
Set of squeeze characters. Walk each line tracking the previous emitted character. Skip the current char only if it's in the squeeze set AND it equals prev.
if (squeeze.has(ch) && ch === prev) continue;
out += ch;
prev = ch;
The full solution:
class Solution {
trSqueeze(lines, chars) {
let squeeze = new Set(chars);
let result = [];
for (let i = 0; i < lines.length; i++) {
let out = "";
let prev = "";
for (let j = 0; j < lines[i].length; j++) {
let ch = lines[i][j];
if (squeeze.has(ch) && ch === prev) {
continue;
}
out += ch;
prev = ch;
}
result.push(out);
}
return result.join("\n");
}
}
Free plan: 30 tutor messages. Premium is unlimited.
