Problem overview
This version builds the -w flag of grep. The function grep_word takes a Vec<String> of lines and a pattern that is a single word made of letters, digits and underscores. It returns the lines that contain the pattern as a whole word, joined with \n. A match is a whole word when the character just before it and the character just after it are not word characters, where a word character is a letter, a digit or an underscore. The match is case-sensitive, and the lines are ASCII.
With pattern = "cat" and lines = ["cat sat", "concat", "the cat", "category"], the result is "cat sat\nthe cat". "concat" is rejected because the letter n comes right before cat, and "category" is rejected because the letter e comes right after it. A line with several occurrences is kept if at least one of them is a whole word, so "concat cat" is selected because of its second cat.
Approach: find every occurrence and check its neighbours
A plain contains isn't enough, because it only says that the text appears somewhere. The first occurrence might be inside a longer word, with a later one standing alone. So the function must look at every occurrence of the pattern in the line, one at a time, and test the bytes on both sides of it.
For an occurrence that starts at byte position pos and has length m, the left neighbour is at pos - 1 and the right neighbour is at pos + m. Each side can also be the edge of the line, which counts as a boundary: there is no character there, so it can't be a word character.
- The left side is fine when
pos == 0or the byte atpos - 1isn't a word character. - The right side is fine when
pos + mequals the line's length, or the byte atpos + misn't a word character.
When both sides are fine, the line is selected and the search stops, since one whole-word occurrence is enough.
For "concat cat", the occurrences of cat start at positions 3 and 7. At 3 the left neighbour is n, so the left check fails. At 7 the left neighbour is a space and the match ends at the end of the line, so both checks pass and the line is kept. For "category" the only occurrence starts at 0, and the right neighbour is e, so the right check fails.
Step by step
- Create the result vector as a
let mutVec<String>. The starter code already providesis_word_char, which tells whether a byte is a letter, a digit or an underscore. - Store the pattern's length in
m. It is needed to find the byte just after a match. - Loop over the lines with
for line in &lines. - View the line as bytes with
line.as_bytes(). Bytes can be read by position, which makes it easy to look at neighbours. - Store the line's length in
n. It marks the right edge. - Start a flag
foundatfalse. It becomes true when this line has a whole-word match. - Loop over the occurrences with
line.match_indices(pattern.as_str()). Each item is a pair of the position and the matched text, and the pattern(pos, _)keeps the position and ignores the text. - Check the left side and store it in
left_ok:posis 0, or the byte before the match is not a word character. - Check the right side and store it in
right_ok: the match ends exactly at the end of the line, or the byte after it is not a word character. - Require both with
if left_ok && right_ok. - Record the hit and stop. Set
foundtotrueandbreakout of the loop over occurrences. Looking further would be wasted work. - After the occurrence loop, test
foundwith anif. - Keep the line. Push
line.clone()ontoresult. - Join and return with
result.join("\n"), after the loop over lines. It is the empty string when nothing was kept.
The solution in Rust
impl Solution {
fn is_word_char(c: u8) -> bool {
(c >= b'a' && c <= b'z')
|| (c >= b'A' && c <= b'Z')
|| (c >= b'0' && c <= b'9')
|| c == b'_'
}
fn grep_word(lines: Vec<String>, pattern: String) -> String {
let mut result: Vec<String> = Vec::new();
let m = pattern.len();
for line in &lines {
let bytes = line.as_bytes();
let n = bytes.len();
let mut found = false;
for (pos, _) in line.match_indices(pattern.as_str()) {
let left_ok = pos == 0 || !Solution::is_word_char(bytes[pos - 1]);
let right_ok = pos + m == n || !Solution::is_word_char(bytes[pos + m]);
if left_ok && right_ok {
found = true;
break;
}
}
if found {
result.push(line.clone());
}
}
result.join("\n")
}
}
Rust details worth knowing:
- Short-circuit evaluation protects the indexing. In
pos == 0 || ... bytes[pos - 1], the right side runs only whenposis not 0. Otherwisepos - 1would underflow ausize, which panics in a debug build and wraps to a huge index in an optimized one, where the indexing would then panic. The same idea protectsbytes[pos + m]: it is read only whenpos + mdiffers fromn, so the index is always valid. - Bytes, not characters.
as_bytes()gives a&[u8], andmatch_indicesreports byte positions, so the two agree. That is whyis_word_chartakes au8and compares it with byte literals such asb'a'. For ASCII text, as in this lesson, one byte is one character. Solution::is_word_char. The helper takes noself, so it is called through the type name.Self::is_word_charis another way to write it.- The tuple pattern.
match_indicesyields(usize, &str). The underscore in(pos, _)discards the matched text, which would be the pattern again. - Non-overlapping matches.
match_indicesdoesn't report overlapping occurrences. In"aaaa", the pattern"aa"is found at positions 0 and 2, not at 1. - The last expression. The function ends with
result.join("\n"), withoutreturnor a semicolon, so that is the value it returns.
Complexity
Time: roughly O(L), where L is the total length of all lines. For each line, match_indices scans the line once, and every occurrence gets a constant-time neighbour check. The loop can stop early on a hit.
Space: O(k), where k is the total length of the kept lines. Viewing a line as bytes copies nothing.
Edge cases and common mistakes
- Checking only the first occurrence. For
"concat cat"the first occurrence is insideconcat. A function that stopped there would wrongly reject the line. The loop must try every occurrence. - Underscores and digits are word characters. For the pattern
"cat", the lines"cat_","cat1"and"_cat"are all rejected."cat","(cat)"and"cat-dog"are accepted, because parentheses and a hyphen are not word characters. - Edges of the line. A match at position 0, or one that ends exactly at the end of the line, has no neighbour on that side. Treat it as a boundary instead of reading outside the line.
- Case. The match is case-sensitive, so
"Cat"doesn't match the pattern"cat". - Substring only.
"xcat"containscatbut not as a whole word, so it is rejected. - No matches. The result is
"", including for an empty list of lines.
Testing
Inputs worth trying, with the results the function returns:
"cat"on["cat sat", "concat", "the cat", "category"]gives"cat sat\nthe cat"."cat"on["concat cat"]gives"concat cat"."cat"on["cat", "cat_", "cat1", "_cat", "(cat)", "cat-dog", "Cat"]gives"cat\n(cat)\ncat-dog"."dog"on["a cat, a dog"]gives"a cat, a dog"."cat"on["xcat"]gives"".
