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:
string trSqueeze(vector<string> lines, string chars)
Example:
Input: lines = ["aaabbb", "abaa"], chars = "a" Output: "abbb\naba" When printed: abbb aba
Put every char of
chars into an unordered_set<char>. Walk each line tracking char prev = '\0'; skip the current char only if it's in the squeeze set AND equals prev.
The full solution:
class Solution {
public:
string trSqueeze(vector<string> lines, string chars) {
unordered_set<char> squeeze;
for (int i = 0; i < chars.size(); i++) {
squeeze.insert(chars[i]);
}
string result;
for (int i = 0; i < lines.size(); i++) {
if (i > 0) result += "\n";
char prev = '\0';
for (int j = 0; j < lines[i].size(); j++) {
char ch = lines[i][j];
if (squeeze.count(ch) && ch == prev) {
continue;
}
result += ch;
prev = ch;
}
}
return result;
}
};
Free plan: 30 tutor messages. Premium is unlimited.
