Problem overview
The method grepWord(lines, pattern) is the -w flag of the Unix grep command. It returns the lines that contain the pattern as a whole word, joined by "\n". The pattern is a single word made of letters, digits and underscores, the match is case-sensitive, and the lines are plain ASCII. A match counts only if the characters right before and right after it are not word characters (letters, digits or underscores), or if the match touches the start or end of the line.
With pattern = "cat" and lines = ["cat sat", "concat", "the cat", "category"], the result is "cat sat\nthe cat". "concat" is rejected because the cat inside it follows an n, and "category" because it is followed by e. A line may contain the pattern several times and is kept if at least one occurrence is a whole word: "concat cat" is kept because of its second cat. No match gives "".
Approach: a regular expression with word boundaries
The earlier grep versions used includes, which cannot tell cat from the middle of concat. Checking the neighbouring characters by hand is possible but fiddly, especially because the first cat in a line may be a bad match while a later one is good. A regular expression expresses the rule directly.
In a regex, \b is a word boundary: a position between a word character and a non-word character, or between a word character and the start or end of the text. Wrapping the pattern as \bcat\b therefore means "cat, with a boundary on each side". The regex engine tries every position in the line, so a later good occurrence is found automatically.
The pattern arrives as a string, so the regex is built once with new RegExp(...) before the loop and then tested against each line. Only the test changes from the earlier versions; the collect-and-join structure stays the same.
Step by step
- Create
resultas an empty array for the matching lines. - Build
regexwithnew RegExp("\\b" + pattern + "\\b"). In a JavaScript string,"\\b"is a backslash followed byb, which is what the regex needs. Because the pattern contains only letters, digits and underscores, none of its characters have a special meaning in a regex, so it needs no escaping. - Loop over the positions with
for (let i = 0; i < lines.length; i++). - Test the line with
regex.test(lines[i]). It returnstruewhen the regex matches anywhere in the text, and one whole-word match is enough to keep the line. - Push
lines[i]ontoresultinside theif. - Return
result.join("\n")after the loop.
The solution in JavaScript
class Solution {
grepWord(lines, pattern) {
let result = [];
let regex = new RegExp("\\b" + pattern + "\\b");
for (let i = 0; i < lines.length; i++) {
if (regex.test(lines[i])) {
result.push(lines[i]);
}
}
return result.join("\n");
}
}
Details that matter here:
- The doubled backslashes. In a normal string literal,
"\b"is the backspace character, one character long, not a regex boundary. Writing"\\b"gives the two characters\b, whichRegExpreads as a word boundary. Forgetting to double the backslash silently breaks the match. - What counts as a word character. For
\b, letters, digits and the underscore are word characters. Socat_xdoes not matchcatas a whole word, whilecat-xdoes, because the hyphen is not a word character. - No
gflag. The regex is created without flags, sotestkeeps no state between calls and the same object can safely check every line. - Case. Without the
iflag the regex is case-sensitive, as the task requires:"Cat"is not a match forcat.
Complexity
Each line is scanned once by the regex engine. For a fixed word pattern the work is roughly proportional to the line length times the pattern length, so the total is bounded by the text size times the pattern length. Building the regex costs time proportional to the pattern, and happens once.
Edge cases and common mistakes
- Single backslashes in the string.
"\bcat\b"builds a pattern full of backspace characters and finds nothing. - Prefix or suffix matches.
"concat"and"category"must be rejected, which plainincludeswould not do. - Repeated pattern.
"concat cat"is kept, since one occurrence is a whole word. - Underscore and digits.
"cat_x"is rejected;"cat-x"is kept. - Pattern with special characters. This solution relies on the pattern holding only letters, digits and underscores. A pattern such as
a.bwould be read as a regex, where.matches any character.
Testing
| lines | pattern | result |
|---|---|---|
["cat sat", "concat", "the cat", "category"] | "cat" | "cat sat\nthe cat" |
["concat cat", "cat_x", "cat-x", "cat", "Cat"] | "cat" | "concat cat\ncat-x\ncat" |
["concat"] | "cat" | "" |
