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:
public String grepCaseInsensitive(List<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.
Lowercase the pattern once, then for each line check
line.toLowerCase().contains(lowerPattern). Push the ORIGINAL line on a hit.
The full solution:
class Solution {
public String grepCaseInsensitive(List<String> lines, String pattern) {
List<String> result = new ArrayList<>();
String lowerPattern = pattern.toLowerCase();
for (String line : lines) {
if (line.toLowerCase().contains(lowerPattern)) {
result.add(line);
}
}
return String.join("\n", result);
}
}
Free plan: 30 tutor messages. Premium is unlimited.
Saved
Ctrl + Enter to check
