Start learning free

LESSON 394 OF 409 · PROJECTS: COMMAND-LINE TOOLS

CLI Tool: tr v3 — Delete Chars (-d) in C++

Practice

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:

string trDelete(vector<string> lines, string chars)

Example:

Input: lines = ["banana", "apple"], chars = "aeiou"

Output: "bnn\nppl"

When printed:
bnn
ppl

Put each character of chars into an unordered_set<char>. Walk every line and append characters that are NOT in the set.

The full solution:
class Solution {
public:
    string trDelete(vector<string> lines, string chars) {
        unordered_set<char> set;
        for (int i = 0; i < chars.size(); i++) {
            set.insert(chars[i]);
        }
        string result;
        for (int i = 0; i < lines.size(); i++) {
            if (i > 0) result += "\n";
            for (int j = 0; j < lines[i].size(); j++) {
                if (set.find(lines[i][j]) == set.end()) {
                    result += lines[i][j];
                }
            }
        }
        return result;
    }
};

STEP 1 OF 10
    Ctrl + Enter to check

    Tr V3 in C++

    Keep going with C++About 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free