Problem overview
This version adds the -w flag of grep. grepWord(lines: List[String], pattern: String): String returns the lines that contain pattern as a whole word, joined by \n. The pattern is a single word made of letters, digits and underscores. A match counts as a whole word when the characters just before and just after it are not word characters (letters, digits or underscores), or when the match touches the start or end of the line. The match is case-sensitive, and the lines are plain ASCII.
With pattern = "cat" and lines = ["cat sat", "concat", "the cat", "category"], the result is "cat sat\nthe cat". The line "concat" is rejected because cat follows the word character n, and "category" because cat is followed by e.
A line is selected if at least one occurrence is a whole word. With "cat", the line "concat cat" is selected because of its second cat, even though the first one is inside concat. If no line matches, the result is "".
Approach
A plain contains can't tell cat from concat, since both contain the letters. Checking the neighbouring characters by hand is possible, but it needs care at the ends of the line and with lines where the pattern occurs several times. A regular expression does this directly, thanks to the word boundary \b.
\b matches a position, not a character: the spot between a word character and a non-word character, or at the edge of the text next to a word character. The regex \bcat\b therefore matches cat in "the cat" and in "cat-dog" (a hyphen is not a word character), but not in "concat", "category" or "cat_dog" (an underscore is a word character).
One more precaution: the pattern is inserted into the regex, so any special character in it would be read as regex syntax. Pattern.quote wraps the text so that it is matched literally. For a pattern made of letters, digits and underscores this changes nothing, but it keeps the regex safe whatever the pattern holds.
The regex is built once, before the loop, and then tried on each line with find(), which looks for a match anywhere in the line. As soon as any occurrence is a whole word, find() returns true, so repeated occurrences are handled for free.
Step by step
- Create the buffer. A
valnamedresultholds the growing list of matching lines. The reference solution uses avarholding aListBuffer, which would also work as aval, since it is never reassigned. - Build the regex once. Compile
"\\b", thenPattern.quote(pattern), then"\\b"withjava.util.regex.Pattern.compile. In a Scala string the backslash is written twice. - Loop over the lines with
for (line <- lines). - Test the line.
regex.matcher(line)creates a matcher for this line, andfind()is true when the regex matches anywhere in it. - Keep the match. Append
lineto the buffer with+=. - Join and return with
result.mkString("\n").
The solution in Scala
class Solution {
def grepWord(lines: List[String], pattern: String): String = {
var result = scala.collection.mutable.ListBuffer[String]()
val regex = java.util.regex.Pattern.compile("\\b" + java.util.regex.Pattern.quote(pattern) + "\\b")
for (line <- lines) {
if (regex.matcher(line).find()) {
result += line
}
}
result.mkString("\n")
}
}
Language details:
- Scala code can use Java's library directly.
java.util.regex.Patternis Java's regex class, written here with its full name. - The two
"\\b"literals contain a backslash and ab. If they were written"\b", Scala would read that as a backspace character, not a word boundary. ListBufferis another growable mutable collection, much likeArrayBuffer;+=appends to it.- The last expression,
result.mkString("\n"), is the method's value, so noreturnis needed. In Scala the last expression of a block is its value. - The
varis never reassigned, sovalwould express the intent better.
Complexity
The regex is compiled once. Each line is then scanned once by the matcher, so the time is roughly proportional to the total size of the input. The buffer holds at most one reference per line, so the extra space is O(n) plus the result string.
Edge cases and common mistakes
- Using
contains. It would acceptconcatandcategory. - Checking only the first occurrence.
"concat cat"must be selected. The regex approach finds the later whole-word occurrence on its own. - Treating underscores as separators.
"cat_dog"is not a match forcat, because_is a word character. A hyphen or a dot, on the other hand, ends a word. - Single backslashes. Without doubling them in the Scala string, the boundary markers don't mean what you intend.
- Skipping
Pattern.quote. A pattern containing.would match any character. With the quote, the patterna.bmatches only a literal dot. - Case. The match is case-sensitive, so
"Cat"is not a match forcat.
Testing
| lines | pattern | Result |
|---|---|---|
List("cat sat", "concat", "the cat", "category") | "cat" | "cat sat\nthe cat" |
List("concat cat", "cat_dog", "cat-dog", "Cat") | "cat" | "concat cat\ncat-dog" |
List("a.b", "axb", "a.b.") | "a.b" | "a.b\na.b." |
List("x") | "z" | "" |
