Start learning free

LESSON 28 OF 69 · PROJECTS: COMMAND-LINE TOOLS

Tr V4 in C++: Squeezing Repeated Characters with continue

Practice Read the full explanation

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;
    }
};

STEP 1 OF 14
    Ctrl + Enter to check

    C++ · PROJECTS: COMMAND-LINE TOOLS

    Tr V4 in C++, explained

    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

    1. Create an unordered_set<char> named squeeze for the characters to squeeze.
    2. Loop over the positions of chars with int i.
    3. Insert each character into squeeze.
    4. Create an empty result string.
    5. Loop over the lines with int i.
    6. Add a newline when i > 0, in a one-line if.
    7. Declare char prev = '\0' inside the loop, so every line starts with no previous character.
    8. Loop over the characters of lines[i] with int j.
    9. Store the current character in char ch.
    10. Test squeeze.count(ch) && ch == prev: a squeeze character that repeats the previous one.
    11. Inside it, write continue, which jumps to the next character, so this one is not added.
    12. After the if, append ch to result. Characters that were not skipped are kept.
    13. Set prev = ch so the next character is compared with this one.
    14. Return result after 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:

    • continue skips the rest of the loop body. It ends the current pass of the inner for and goes on with j + 1. Neither result += ch nor prev = ch runs for a skipped character. That is fine, because the skipped character equals prev already.
    • count and &&. squeeze.count(ch) is 0 or 1, so it works as a condition. The && operator stops at the first false part: when ch is not in the set, ch == prev is never evaluated.
    • '\0' is a char. It is the character with code 0. Single quotes make a character, double quotes make a string, so prev = '\0' is correct and prev = "\0" would not compile.
    • prev lives 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 a b the previous character is b, so in "abaa" the a after the b is 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 capital A is 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

    linescharsresult
    {"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"
    Keep going with C++1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free