Problem overview
Grep takes a List<string> named lines and a search pattern, and returns every line that contains the pattern, in their original order, joined by newline characters (\n). The search is case-sensitive, and the pattern is plain text: a . or * means itself, not a wildcard as in a regular expression.
For pattern "err" and lines ["error: foo", "warning", "another error", "ok"], the first and third lines contain err, so the result is "error: foo\nanother error". Printed, that is two lines. If nothing matches, the result is the empty string.
Approach
This is a filter: look at each line, keep it if it passes a test, and drop it otherwise. The test is the string method Contains, which is true when the pattern appears anywhere in the line, at the start, in the middle or at the end.
You do not know how many lines will match, so the kept lines go in a List<string>. A list grows as you add to it, while an array has a fixed length chosen when it is created. At the end the list is turned into one string with a newline between each pair of lines.
Step by step
- Create
result, a new emptyList<string>. The matches will be collected here. - Loop over
lineswithforeach, naming each entryline. - Test the line with an
ifonline.Contains(pattern). - Add the line to
resultinside theif, withresult.Add(line). Only lines that passed the test get there. - Return the joined text with
string.Join("\n", result), after the loop.
The solution in C#
class Solution {
public string Grep(List<string> lines, string pattern) {
List<string> result = new List<string>();
foreach (string line in lines) {
if (line.Contains(pattern)) {
result.Add(line);
}
}
return string.Join("\n", result);
}
}
The details worth knowing:
Containsis case-sensitive."Error".Contains("err")isfalse. Matching ignoring case is the next lesson.Containsis literal."a.b".Contains("a.b")istrueand"axb".Contains("a.b")isfalse: the dot is an ordinary character, which is exactly the plain-text behaviour the statement asks for.string.Join(separator, list)puts the separator only between items, never after the last one. A single match gives that line with no newline, and an empty list gives"", so the "no match" case needs noif."\n"is one character. The escape is a newline, not a backslash followed by ann.- The original line is kept. Nothing is changed, so the returned lines are the same strings that came in.
Complexity
Let n be the number of lines and m the length of the longest one. Time: each line is searched once, and a search takes at most about the line's length times the pattern's length in the worst case, so the total is at most proportional to n times m times the pattern length. In practice searches for short patterns are fast. Space: the result list holds the matching lines, so it is O(n) references in the worst case, plus the joined string.
Edge cases and common mistakes
- No matches. The list stays empty and the method returns
"". - Every line matches. The result is all the lines, joined by newlines, in the original order.
- Trailing newline. Building the text with
+= line + "\n"leaves a newline at the end, which is not what the expected output has.string.Joinavoids it. - Using
==instead ofContains.line == patternonly matches when the whole line equals the pattern. - Checking the start only.
StartsWithwould reject"another error", which the example keeps.
Testing
- Pattern
"err"with the four lines above gives"error: foo\nanother error". - Pattern
"ERR"with the same lines gives"". - Pattern
"a.b"with["a.b", "axb"]gives"a.b".
