Problem overview
The function grep takes a vector<string> named lines and a string named pattern. It returns every line that contains pattern as a substring, in their original order, joined by newline characters. The match is case-sensitive, and the pattern is plain text: characters such as . and * mean nothing special. If no line matches, the function returns the empty string.
In the example, pattern = "err" and the lines are ["error: foo", "warning", "another error", "ok"]. Lines 1 and 3 contain err, so the result is "error: foo\nanother error".
Approach: test each line, glue the matches
The work has two parts: deciding whether a line matches, and joining the matching lines with newlines between them but not after the last one.
For the first part, string::find searches a string for a substring and returns the position of the first match. When there is no match it returns the special value string::npos. So a line contains the pattern exactly when lines[i].find(pattern) != string::npos. Comparing with npos is the correct test, because a match at the very start has position 0.
For the second part, the function builds the result one piece at a time. A bool flag named first remembers whether any line has been added yet. The first line goes in without a newline in front, and every later line gets one. This way the separator only ever sits between two lines.
Step by step
- Create an empty
stringnamedresult. The matching lines are appended to it. - Create
bool first = true. It means no line has been added yet. - Loop over the lines by position with
ifrom 0 whilei < lines.size(). - Test the line with
lines[i].find(pattern) != string::npos. Everything else happens inside thisif, so non-matching lines are skipped. - Add the separator with
if (!first) result += "\n";. For the very first match nothing is added. - Append the line with
result += lines[i]. - Set
firsttofalseso later matches get their newline. - Return
resultafter the loop. If nothing matched,resultwas never touched and is still the empty string the statement asks for.
The solution in C++
class Solution {
public:
string grep(vector<string> lines, string pattern) {
string result;
bool first = true;
for (int i = 0; i < lines.size(); i++) {
if (lines[i].find(pattern) != string::npos) {
if (!first) result += "\n";
result += lines[i];
first = false;
}
}
return result;
}
};
The C++ details worth a closer look:
findreturns a position, not a yes or no. The type issize_t, an unsigned integer, andnposis the largest value of that type. That is why the test compares withstring::nposand not with a number such as-1written by hand.- The test is on the whole line. A
findresult greater than 0 would miss a pattern at the start of a line, where the position is 0. - Why a flag and not
result.empty(). Checking whetherresultis empty fails when a matching line is itself empty, as with an empty pattern, because the result is still empty after it is added. The flag records that a line was added, whatever its text. - The result is built in place.
+=appends to the end of astring. The two+=operations in the loop do the whole joining; no separate join function is needed. - The empty pattern.
find("")succeeds at position 0 in every string, so an empty pattern matches every line.
Complexity
Time. Let m be the pattern length and let the lines have lengths n1, n2 and so on. A plain substring search of a line of length n may need up to about n * m character comparisons in the worst case, so the total is bounded by the sum of those products. Appending the matching lines costs time proportional to their total length. For typical short patterns it behaves like a single pass over the text.
Space: O(total length). The result holds a copy of every matching line, and the by-value parameters copy the input.
Edge cases and common mistakes
- No match.
["ok", "fine"]with pattern"err"gives"". - Case matters.
["Error", "error"]with pattern"err"gives"error":"Error"has a capital E, so it doesn't containerr. - Special characters are plain text.
["a.b", "abc"]with pattern"."gives"a.b". In a regular expression the dot would match every character, but here it only matches a dot. - Empty pattern.
["x", "y"]with pattern""gives"x\ny", since every line contains the empty string. - Empty lines that match.
["", "a"]with pattern""gives"\na": the empty line is kept, and the newline after it is still added. - Newline in the wrong place. Adding
"\n"after every line leaves a trailing newline, which the expected result doesn't have. - Matching only at the start. Using
find(pattern) == 0selects lines that begin with the pattern, not lines that contain it.["cat food", "the cat"]with pattern"cat"must return both.
Testing
["error: foo", "warning", "another error", "ok"]with"err"gives"error: foo\nanother error".["cat food", "the cat"]with"cat"gives"cat food\nthe cat".["ok", "fine"]with"err"gives"".["a.b", "abc"]with"."gives"a.b".
