Problem overview
This version builds the -v flag of grep, which inverts the match. The function grep_invert takes a Vec<String> of lines and a pattern, and returns every line that does not contain the pattern. The check is case-sensitive, the lines stay in their original order, and they are joined with \n. When every line contains the pattern, the result is the empty string.
For pattern = "err" and lines = ["error", "ok", "another error", "fine"], the lines with err are dropped and the result is "ok\nfine".
Approach: the same filter with the test flipped
The first grep version kept a line when contains was true. This version keeps it when contains is false. Nothing else changes: the loop, the vector of kept lines and the final join("\n") are the same.
In Rust, the logical negation is the prefix operator !. Writing !line.contains(...) applies it to the whole call: the method runs first, and its boolean result is flipped. There is no not keyword in Rust.
The empty result needs no special code. If every line contains the pattern, nothing is ever pushed, the vector stays empty, and joining an empty vector gives "".
Step by step
- Create the result vector as a
let mutVec<String>that will hold the lines without the pattern. - Loop over the lines by reference with
for line in &lines. The vector is only borrowed, so it is still there after the loop. - Test for absence. Put
!in front ofline.contains(pattern.as_str()). The condition is now true exactly for lines that do not contain the pattern. The lesson passespattern.as_str(), which turns theStringinto a plain text slice forcontains. - Keep the line. Inside the
if,result.push(line.clone())adds an owned copy of the line. - Join and return.
result.join("\n")separates the kept lines with newlines and gives the empty string when none were kept.
The solution in Rust
impl Solution {
fn grep_invert(lines: Vec<String>, pattern: String) -> String {
let mut result: Vec<String> = Vec::new();
for line in &lines {
if !line.contains(pattern.as_str()) {
result.push(line.clone());
}
}
return result.join("\n");
}
}
Rust details worth knowing:
pattern.as_str()against&pattern. Both work as the argument ofcontains.as_str()returns a&strview of theString's contents without copying them, and theStringremains usable afterwards.- Precedence of
!. A method call binds tighter than the prefix!, so!line.contains(x)means!(line.contains(x)). No extra parentheses are needed. - Why
clone().lineis a reference intolines. The result vector must own its strings, so each kept line is copied. joinand empty input. Joining a vector with one element returns that element, and joining an empty vector returns the empty string.
Complexity
Time: roughly O(m), where m is the total length of all lines. Each line is searched once, and the kept lines are copied and joined in linear time.
Space: O(k), where k is the total length of the kept lines.
Edge cases and common mistakes
- Every line matches. For
["error", "another error"]and the pattern"err", the result is"". - Case still matters. With the pattern
"err"on["Error", "ok"],"Error"does not contain a lowercaseerr, so both lines are kept:"Error\nok". - Empty lines are lines. An empty line doesn't contain a non-empty pattern, so it is kept. With
["a", "", "b"]and the pattern"z", the result is"a\n\nb", which has a blank line in the middle. - Empty pattern. Every line contains the empty string, so nothing is kept and the result is
"". - Empty list. The loop doesn't run, and the result is
"". - Forgetting the
!. Without it the function behaves like the previous version and returns the opposite set of lines. - Negating the wrong thing. Pushing the line in an
elsebranch is an equivalent option, but flipping the condition is shorter.
Testing
Inputs worth trying, with the results the function returns:
"err"on["error", "ok", "another error", "fine"]gives"ok\nfine"."err"on["error", "another error"]gives""."err"on["Error", "ok"]gives"Error\nok"."z"on["a", "", "b"]gives"a\n\nb".- An empty pattern on
["a", "b"]gives"".
