Build the -i flag of the Unix grep command. Given a list of lines and a search pattern, return all lines that contain pattern as a substring, ignoring letter case. Return the matching lines joined by newline characters (\n).
Function signature:
string grepCaseInsensitive(vector<string> lines, string pattern)
Example:
Input: pattern = "ERR" lines = ["Error: 1", "ok"] Output: "Error: 1" When printed: Error: 1
The matching is case-insensitive but the original line (preserving its original casing) is returned. If no lines match, return the empty string "". The lines contain only ASCII characters.
Write a small
toLower helper that walks the string and lowercases each character with tolower(). Use it on both the pattern (once) and each line.
string toLower(string s) {
for (int i = 0; i < s.size(); i++) {
s[i] = tolower(s[i]);
}
return s;
}
The full solution:
class Solution {
public:
string toLower(string s) {
for (int i = 0; i < s.size(); i++) {
s[i] = tolower(s[i]);
}
return s;
}
string grepCaseInsensitive(vector<string> lines, string pattern) {
string result;
bool first = true;
string lowerPattern = toLower(pattern);
for (int i = 0; i < lines.size(); i++) {
if (toLower(lines[i]).find(lowerPattern) != string::npos) {
if (!first) result += "\n";
result += lines[i];
first = false;
}
}
return result;
}
};
Free plan: 30 tutor messages. Premium is unlimited.
Saved
Ctrl + Enter to check
