Problem overview
This is a small version of the Unix grep command. The function grep takes a Vec<String> of lines and a pattern, and returns every line that contains the pattern as a substring. The match is case-sensitive, and the kept lines are joined with \n into one String. If no line matches, the result is the empty string.
With pattern = "err" and lines = ["error: foo", "warning", "another error", "ok"], the result is "error: foo\nanother error". Printed, it shows two lines: error: foo and another error. The pattern is plain text. In the real tool, characters such as . and * have special meanings in a pattern; here they mean nothing special and are matched literally.
Approach: test each line, keep the ones that pass
This is a filter: look at every line, decide whether it matches, and collect the matches in their original order. Rust's str::contains does the deciding. It reports whether the given text appears anywhere inside the string, not just at its start, so "another error" matches "err" even though it doesn't begin with it.
The kept lines go into a Vec<String>, and a single join("\n") at the end produces the output. Joining is better than appending "\n" after every line, because the separator belongs only between two lines. A manual loop that adds a newline each time leaves a stray newline at the end that the expected output doesn't have.
Step by step
- Create an empty result vector. It has type
Vec<String>, is made withVec::new(), and needslet mutbecause every kept line changes it. - Loop over the lines by reference.
for line in &linesborrows the vector, so it still exists after the loop, andlineis a&Stringon each pass. - Test the line.
line.contains(&pattern)is true when the pattern appears anywhere in the line. The&lends the pattern tocontainsinstead of moving it, so it can be reused for the next line. - Keep the line. Inside the
if,result.push(line.clone())adds a copy. The vector needs its ownString, andlineis only a borrowed reference. - Join and return.
result.join("\n")glues the kept lines with a newline between each two. With an emptyresultit returns the empty string, which is exactly what the problem asks for when nothing matched.
The solution in Rust
impl Solution {
fn grep(lines: Vec<String>, pattern: String) -> String {
let mut result: Vec<String> = Vec::new();
for line in &lines {
if line.contains(&pattern) {
result.push(line.clone());
}
}
return result.join("\n");
}
}
Rust details worth knowing:
- Borrowing the pattern.
containsaccepts several kinds of pattern, such as a&str, acharor a closure. A&Stringworks too. Passingpatternwithout the&would move theStringinto the first call and fail to compile on the second pass of the loop. clone(). The loop only borrows the lines, and aVec<String>can't hold borrowed references without extra lifetime annotations.clone()makes an owned copy, which costs an allocation per kept line.joinon a vector of strings.Vec<String>has ajoinmethod that takes the separator and returns aString. A vector with one item gives that item with no separator, and an empty vector gives"".- Explicit
return. Ending the function with the bare expressionresult.join("\n")would work as well.
Complexity
Time: roughly O(m), where m is the total length of all lines. Every line is searched once, and the standard library's substring search is linear in the line's length plus the pattern's length. Copying the kept lines and joining them is linear in their total length.
Space: O(k), where k is the total length of the kept lines, because the result holds copies of them.
Edge cases and common mistakes
- No matches. For
pattern = "zzz"on the example lines, the function returns the empty string. - Case matters. With
pattern = "Err", the example gives the empty string, because the lines contain a lowercaseerronly. - Special characters are plain text. With
["a.c", "abc", "a*c"]and the pattern"a.c", only"a.c"is returned..doesn't match any character here. - Empty pattern. Every string contains the empty string, so an empty pattern keeps all lines. With
["a.c", "abc"]the result is"a.c\nabc". - Empty list. The loop doesn't run and the result is
"". - Trailing newline. Joining puts the separator only between lines. Building the output by adding
"\n"after each kept line would add an extra one at the end. - Checking only the start.
starts_withis a different test. The problem wants the pattern anywhere in the line.
Testing
Inputs worth trying, with the results the function returns:
"err"on["error: foo", "warning", "another error", "ok"]gives"error: foo\nanother error"."zzz"on the same lines gives""."a.c"on["a.c", "abc", "a*c"]gives"a.c"."only"on["only"]gives"only".- Any pattern on an empty vector gives
"".
