Problem overview
Version 4 of the tr tool adds squeezing, like tr -s. The method trSqueeze(vector<string> lines, string chars) collapses each run of the same character into one occurrence, but only for characters that appear in chars. Other characters, and runs of characters not in chars, are left alone. The lines are returned joined by \n.
chars is a non-empty ASCII string, taken literally, and case matters. Lines may be empty. With {"aaabbb", "abaa"} and chars = "a" the result is "abbb\naba": the run of a at the start of the first line shrinks to one, the b run stays, and in the second line the final aa shrinks to one a.
Approach
A character is dropped when two things are true: it is one of the squeeze characters, and it is the same as the character just before it in the output. The first character of a run is always kept, and the repeats after it are skipped.
The first condition is a membership test, so an unordered_set<char> fits, as in version 3. The second needs a little memory: a variable prev that holds the last character added to result for the current line. Comparing against the previous kept character is enough, because a skipped character is equal to it anyway.
prev must restart for every line. Without that, a line that begins with the character that ended the previous line would be squeezed against it, although the two are on different lines. The lesson sets prev to '\0', the null character, at the start of each line. It stands for "nothing yet" and, for ordinary text, never equals a real character.
Only runs of one character collapse. In "abab" with chars = "ab" no character repeats right after itself, so nothing changes, even though both letters are in the set.
Step by step
- Create an
unordered_set<char>namedsqueezefor the characters to squeeze. - Loop over the positions of
charswithint i. - Insert each character into
squeeze. - Create an empty
resultstring. - Loop over the lines with
int i. - Add a newline when
i > 0, in a one-lineif. - Declare
char prev = '\0'inside the loop, so every line starts with no previous character. - Loop over the characters of
lines[i]withint j. - Store the current character in
char ch. - Test
squeeze.count(ch) && ch == prev: a squeeze character that repeats the previous one. - Inside it, write
continue, which jumps to the next character, so this one is not added. - After the
if, appendchtoresult. Characters that were not skipped are kept. - Set
prev = chso the next character is compared with this one. - Return
resultafter the outer loop.
The solution in C++
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;
}
};
The details worth knowing:
continueskips the rest of the loop body. It ends the current pass of the innerforand goes on withj + 1. Neitherresult += chnorprev = chruns for a skipped character. That is fine, because the skipped character equalsprevalready.countand&&.squeeze.count(ch)is 0 or 1, so it works as a condition. The&&operator stops at the first false part: whenchis not in the set,ch == previs never evaluated.'\0'is achar. It is the character with code 0. Single quotes make a character, double quotes make a string, soprev = '\0'is correct andprev = "\0"would not compile.prevlives inside the outer loop. Declaring it there creates it fresh for each line. Moving the declaration above the loop would carry the last character over to the next line.- Chars outside the set still update
prev. After abthe previous character isb, so in"abaa"theaafter thebis kept.
Complexity
The code visits each input character once and does a set lookup and a few comparisons, each constant time on average. The total time is proportional to the length of chars plus the total number of input characters. The extra space is the set and the result string.
Edge cases and common mistakes
- Runs of the squeeze character.
{"aaabbb"}with"ab"gives"ab", since both runs shrink. - Spaces.
{"a b c"}with" "gives"a b c". - Case.
{"aAaa"}with"a"gives"aAa": the capitalAis a different character, so it separates the runs. - No repeats.
{"abab"}with"ab"returns"abab". - Lines are independent.
{"aab", "aab"}with"a"gives"ab\nab". Each line is squeezed on its own, and the newline is never treated as part of a run. - Empty lines.
{"", "xx"}with"x"gives"\nx". - Squeezing every character. Dropping any repeat, whether or not it is in
chars, would also turn"bbb"into"b". The membership test prevents that. - Empty input. An empty vector returns
"".
Testing
| lines | chars | result |
|---|---|---|
{"aaabbb", "abaa"} | "a" | "abbb\naba" |
{"aaabbb"} | "ab" | "ab" |
{"a b c"} | " " | "a b c" |
{"aAaa"} | "a" | "aAa" |
{"aab", "aab"} | "a" | "ab\nab" |
{"abab"} | "ab" | "abab" |
{"", "xx"} | "x" | "\nx" |
