Problem overview
Version 3 of the tr tool adds deletion, like tr -d. The method trDelete(vector<string> lines, string chars) removes from every line each character that appears in chars, then returns the lines joined by \n.
chars is a non-empty ASCII string, taken literally with no ranges, and case matters. A line can become empty after the deletion, and it then stays in the output as an empty line. For {"banana", "apple"} with chars = "aeiou" the result is "bnn\nppl".
Approach
For each character of the input you need one yes-or-no answer: is it one of the characters to delete? Searching chars from the start each time would work, but a set answers the question directly. An unordered_set<char> stores each character once and tests membership in constant time on average.
The rest is the copying loop from the earlier versions, with a change: instead of appending either a replacement or the original character, the loop appends the character only when it is not in the set. A deleted character is simply never copied.
The newline logic stays the same. A newline is added before every line except the first, whatever the line contains. Empty lines are not removed, because the newline is added before checking any characters. A line that loses all its characters leaves only its separator behind.
The difference from version 2 is that nothing is looked up for a replacement. A set is enough when you only need to know whether a character belongs to a group, and a map is needed when each member also carries a value. Choosing the right container is half of the solution here: the loops barely change from version 2, and the container's interface decides how the check is written.
Step by step
- Create an
unordered_set<char>namedsetfor the characters to delete. - Loop over the positions of
charswithint i. - Insert each character with
set.insert(chars[i]). Repeated characters incharsare stored once. - Create an empty
resultstring. - Loop over the lines with
int i. - Add a newline when
i > 0, in a one-lineif. - Loop over the characters of
lines[i]withint j. - Test that the character is missing from the set:
set.find(lines[i][j]) == set.end().findreturnsend()when it finds nothing. - Inside that
if, append the character toresult. - Return
resultafter the outer loop.
The solution in C++
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;
}
};
What to know about the C++ parts:
findreturns an iterator. It points at the element when it is found and equalsset.end()when it is not. Comparing withend()is the standard way to say "not found".set.count(c) == 0is an equivalent test.insertignores duplicates. Inserting a character that is already there changes nothing, sochars = "aabb"behaves like"ab".- A set has no order. The order of
unordered_setelements is unspecified. That doesn't matter here, because the code only asks whether a character is present. - The name
set. A local variable calledsethides the standard containerstd::setinside the function. It compiles and the solution is correct, but a name such astoDeleteis clearer in a bigger program.
The erase-remove alternative
The standard library has an idiom for deleting elements from a string: remove_if moves the characters to keep to the front and returns the new end, and erase then cuts off the leftover tail.
unordered_set<char> del(chars.begin(), chars.end());
// for each line:
string line = lines[i];
line.erase(remove_if(line.begin(), line.end(), [&](char c) { return del.count(c) > 0; }), line.end());
result += line;
With the same newline handling, this returns "bnn\nppl" for the example. It also shows the set built straight from the characters of chars, with no loop. The lesson's version spells out the loops so each step stays visible, and it never needs a temporary copy of a line.
Complexity
Filling the set takes one insertion per character of chars. The main loops make one membership test per input character, each constant time on average. The total time is proportional to the length of chars plus the total input length. The set holds at most as many characters as chars has, and the result holds the characters that survive.
Edge cases and common mistakes
- Deleting everything on a line.
{"aaa", "bab", "c"}with"a"gives"\nbb\nc". The first line becomes empty, so the result starts with a newline. - Case.
{"Hello"}with"hl"gives"Heo": the capitalHstays, and both lowercaselcharacters go. - Deleting commas.
{"a,b", "", ",,"}with","gives"ab\n\n": three lines, the last two empty. Deleting commas does not touch the line breaks, which are added by the loop. - Repeated characters in
chars.{"abc"}with"aabb"gives"c". - Spaces.
{"x y"}with" "gives"xy". - Skipping the newline for empty lines. Adding the newline only when a line has content loses the empty lines, and the tests expect them.
- Empty input. An empty vector returns
"".
Testing
| lines | chars | result |
|---|---|---|
{"banana", "apple"} | "aeiou" | "bnn\nppl" |
{"aaa", "bab", "c"} | "a" | "\nbb\nc" |
{"Hello"} | "hl" | "Heo" |
{"a,b", "", ",,"} | "," | "ab\n\n" |
{"abc"} | "aabb" | "c" |
The next version builds on this one.
