Problem overview
This is the -w flag of grep. The function grepWord takes lines, a vector<string>, 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 newlines. The characters right before and right after the match must not be word characters. The match is case-sensitive, the lines are ASCII, and the result is empty when nothing matches.
With pattern = "cat" and lines ["cat sat", "concat", "the cat", "category"] the result is "cat sat\nthe cat". In "concat" the match is preceded by the word character n, and in "category" it is followed by e. A line can contain the pattern several times and is selected if at least one occurrence is a whole word, so "concat cat" is selected because of its second cat.
Approach: try every position and check both neighbours
Plain find isn't enough here. It reports the first place where the pattern occurs, and that occurrence may be the wrong one: in "concat cat" the first cat is inside a word, and only the second counts. So the function scans the line itself, one start position at a time, and checks each candidate.
At a position pos, the candidate is the m characters of the line starting there, where m is the pattern length. If they equal the pattern, the function looks at the character before (pos - 1) and the character after (pos + m). A boundary is fine when it lies outside the line, or when the neighbour is not a word character. If both sides are fine, the line is selected and the scan stops, because one whole-word match is enough. If not, the scan moves on by one position, so overlapping candidates are not skipped.
The starter code gives the helper isWordChar, which is true for letters, digits and the underscore. The result is built as in the earlier versions, with a first flag controlling the newline separator.
Step by step
- Create
resultandfirst. They work as in version 1: an empty string for the selected lines and a flag meaning that none has been added. - Store the pattern length in
mwithpattern.size(). It locates the character just after a match. - Loop over the lines by position with
ifrom 0 whilei < lines.size(). - Take a
const string&namedlinethat refers tolines[i]. It is a second name for the same string: no copy, and a shorter name. - Store the line length in
n. It marks the right edge. - Create
bool matched = false. Each line starts as not matched. - Create
int pos = 0, the start position of the next candidate. - Loop while
pos + m <= n. A candidate must fit inside the line, so starting later thann - mis pointless. - Compare the candidate with
line.compare(pos, m, pattern) == 0. The call compares themcharacters fromposwith the pattern and returns 0 when they are equal. - Compute
leftOk: true whenpos == 0, or whenline[pos - 1]is not a word character. - Compute
rightOk: true when the match ends at the end of the line (pos + m == n), or whenline[pos + m]is not a word character. - Accept the candidate only if both are true. Then set
matchedtotrueandbreak. - Move to the next position with
pos++, after thecomparecheck and still inside thewhile. Without it the loop would test the same position forever. - After the scan, add the line if
matched: a newline whenfirstis false, then the line, thenfirst = false. - Return
resultafter the outer loop.
The solution in C++
class Solution {
public:
bool isWordChar(char c) {
return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '_';
}
string grepWord(vector<string> lines, string pattern) {
string result;
bool first = true;
int m = pattern.size();
for (int i = 0; i < lines.size(); i++) {
const string& line = lines[i];
int n = line.size();
bool matched = false;
int pos = 0;
while (pos + m <= n) {
if (line.compare(pos, m, pattern) == 0) {
bool leftOk = (pos == 0) || !isWordChar(line[pos - 1]);
bool rightOk = (pos + m == n) || !isWordChar(line[pos + m]);
if (leftOk && rightOk) {
matched = true;
break;
}
}
pos++;
}
if (matched) {
if (!first) result += "\n";
result += line;
first = false;
}
}
return result;
}
};
The C++ details worth a closer look:
- Short-circuit evaluation protects the indexing. In
(pos == 0) || !isWordChar(line[pos - 1]), the right side runs only whenposis above 0, soline[-1]is never evaluated. In the same way,(pos + m == n) || ...skips the read ofline[pos + m]when that index would be one past the end of the line. Swapping the two operands would break both guards. compare(pos, m, pattern). It compares a substring oflinewithpatternwithout creating a temporary string. It returns 0 for equal text, so the test is== 0. Thewhilecondition guarantees thatpos + mnever exceeds the line length, so the call stays inside the string.const string&. A reference to a const string avoids copying the line, andconstpromises that this code won't change it.- Characters are compared with ranges.
c >= 'a' && c <= 'z'works for ASCII because the letters and the digits are contiguous in the character table. The underscore is handled with a separate comparison. intpositions.size()returns an unsigned value. Storing the lengths inintvariables means that expressions such aspos + m <= nandpos - 1follow ordinary signed arithmetic, with no wrap-around at 0.
Complexity
Time. For a line of length n and a pattern of length m, there are at most n - m + 1 candidate positions, and each compare may look at up to m characters. The cost per line is therefore at most about n * m comparisons, and it is much less for most inputs because a comparison stops at the first different character. Appending the selected lines is proportional to their total length.
Space: O(total length). The result holds copies of the selected lines, and the by-value parameters copy the input. The scan itself uses a few integers and no copy of the line.
Edge cases and common mistakes
- Pattern inside a longer word.
["cat", "dog"]with"cats"gives"", and["cat sat", "concat", "the cat", "category"]with"cat"keeps only the first and third lines. - Several occurrences.
["concat cat"]with"cat"returns the line. The first occurrence fails the left test, the scan continues by one position, and the second occurrence passes. - The underscore is a word character.
["cat_x", "a cat, b", "cat", "x-cat-y"]with"cat"gives"a cat, b\ncat\nx-cat-y"."cat_x"is rejected, while a comma or a hyphen next to the match counts as a boundary. - Match at the start or end of the line.
["cat", "the cat", "cats"]with"cat"gives"cat\nthe cat". A line edge counts as a boundary, so the whole line"cat"is a whole word. - Case matters.
["Cat", "cat"]with"cat"gives"cat". - Stepping by
minstead of 1. Skipping ahead by the pattern length after a failed candidate can jump over the start of a later match. Overlapping starts are tested only when the position moves by one. - Using the first
findresult only. That checks one occurrence, so"concat cat"would be rejected. - Forgetting
break. The result is still correct, sincematchedstays true, but the scan keeps going after the answer is known. - Empty list. An empty vector gives
"", because the loop doesn't run.
Testing
["cat sat", "concat", "the cat", "category"]with"cat"gives"cat sat\nthe cat".["concat cat"]with"cat"gives"concat cat".["catcat cat"]with"cat"gives"catcat cat".["cat_x", "a cat, b", "cat", "x-cat-y"]with"cat"gives"a cat, b\ncat\nx-cat-y".["hi"]with"hi there"gives"".
