Build a tiny version of the Unix grep command. Given a list of lines and a search pattern, return all lines that contain pattern as a substring (case-sensitive), joined by newline characters (\n).
Function signature:
grep(lines: string[], pattern: string): string
Example:
Input: pattern = "err" lines = ["error: foo", "warning", "another error", "ok"] Output: "error: foo\nanother error" When printed: error: foo another error
If no lines match, return the empty string "".
Note: real grep treats the pattern as a regular expression by default (grep -F matches plain text). Here the pattern is always plain text: just look for it literally, so characters such as . or * mean nothing special.
Iterate over the lines, keep the ones where
lines[i].includes(pattern) is true, then return result.join("\n").
The full solution:
class Solution {
grep(lines: string[], pattern: string): string {
let result: string[] = [];
for (let i = 0; i < lines.length; i++) {
if (lines[i].includes(pattern)) {
result.push(lines[i]);
}
}
return result.join("\n");
}
}
Free plan: 30 tutor messages. Premium is unlimited.
