Problem overview
The method grepWord takes a List<String> named lines and a pattern, a single word made of letters, digits and underscores. It returns the lines that contain the pattern as a whole word, joined by newline characters. A whole word means the character just before the match and the character just after it must not be word characters (letters, digits or underscores). The match is case-sensitive, and the lines contain only ASCII characters. If nothing matches, the result is "".
For 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 is preceded by n, and "category" is rejected because it is followed by e. A line is selected if at least one occurrence is a whole word, so "concat cat" is selected because of its second cat.
Approach: a regular expression with word boundaries
Plain contains would accept "concat", so the check needs to look at the neighbours of a match. Doing that by hand means finding every occurrence, inspecting the characters on both sides, and moving on to the next occurrence when the first one fails. A regular expression does all of that in one pattern.
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 word in boundaries, \bcat\b, matches cat only where it stands alone. The regex finds the first such place anywhere in the line, and a line with several candidates is checked against all of them.
The pattern text must be treated literally, though. If it were pasted into the regex as it is, a character with a special meaning in regular expressions would change what is matched. Pattern.quote wraps the text so that every character in it counts as itself.
Step by step
- Create
result, an emptyArrayListheld in aList<String>variable. - Build the regex once, before the loop, with
Pattern.compileand keep it in aPatternnamedregex. The text is"\\b", thenPattern.quote(pattern), then"\\b"again. In a Java string literal each backslash is written twice. The class is written asjava.util.regex.Pattern. - Loop over the lines with a for-each loop naming each entry
line. - Search each line.
regex.matcher(line)creates a matcher for that line, andfind()returns true if the regex matches anywhere in it. One whole-word match is enough to keep the line. - Keep the line with
result.add(line). - Join and return with
String.join("\n", result); with no matches this gives"".
The solution in Java
class Solution {
public String grepWord(List<String> lines, String pattern) {
List<String> result = new ArrayList<>();
java.util.regex.Pattern regex = java.util.regex.Pattern.compile("\\b" + java.util.regex.Pattern.quote(pattern) + "\\b");
for (String line : lines) {
if (regex.matcher(line).find()) {
result.add(line);
}
}
return String.join("\n", result);
}
}
The Java details worth a closer look:
- Two
Patterns. The parameterpatternis aString, the text to look for. The variableregexis ajava.util.regex.Pattern, the compiled expression. They are different things with confusingly similar names. The fully qualified class name saves an import; withimport java.util.regex.Pattern;the code could say justPattern. - Why
\\b. The regex is\b. Inside a Java string a backslash begins an escape sequence, so it is doubled. A single"\b"in Java source is a backspace character, which is a different thing entirely. - Why
Pattern.quote. It surrounds the text with\Q...\E, which switches off special meaning. The lesson's patterns are plain words, but without quoting, a pattern likec.twould be read as "c, any character, t". Compiled withoutquote, the regex\bc.t\bfinds a match in"cut"; compiled with it, it does not. find()againstmatches().find()looks for a match anywhere in the text.matches()succeeds only if the regex matches the entire line, so it would reject"the cat".- Compiling once. Building a regex is more expensive than using it, so it is compiled before the loop and reused for every line.
- Imports.
ListandArrayListneedimport java.util.*;in a standalone file.
Complexity
Let n be the number of lines and m the total number of characters in them.
Time: O(m * p) in the worst case, with p as the length of the pattern. The matcher tries each position in each line, and a try compares at most the pattern's characters. Compiling the regex costs O(p) once.
Space: O(n + m), for the result list and the joined string, plus the compiled regex.
Edge cases and common mistakes
- Underscores and digits are word characters. With the pattern
"cat", the lines"cat_x"and"cat1"are rejected, while"cat-x","cat."and"(cat)"are accepted, as is a line that is just"cat". - Case matters.
["Cat", "cat"]with"cat"gives"cat". - The word at the start or end of the line.
\balso matches at the edges of the text, so"cat sat"and"the cat"both match. - No match. An empty list, a list holding one empty line, and a list with no whole word all give
"". - Using
contains. It accepts"concat"and"category". - Forgetting the doubled backslash.
"\b" + ...compiles in Java, but the string holds a backspace character and no line matches. - A dot in the pattern. With the pattern
"a.b", quoting means["a.b", "axb"]returns only"a.b".
Testing
["cat sat", "concat", "the cat", "category"]with"cat"gives"cat sat\nthe cat".["concat cat"]with"cat"gives"concat cat".["cat_x", "cat1", "cat-x", "cat.", "(cat)", "cat"]with"cat"gives"cat-x\ncat.\n(cat)\ncat".["Cat", "cat"]with"cat"gives"cat".[]with"cat"gives"".
