Parse a key=value Config
Problem
The input has configuration lines key=value, then a line with three dashes ---, then query lines with one key each. Spaces around the key and around the value are not part of them. The value may contain more = characters. If a key is set twice, the last value wins. For each query print its value, or missing if the key does not exist.
Constraints
- 1 <= lines <= 10^5
Examples
Input
host = localhost port=8080 --- host user
Output
localhost missing
Solutions
Splitting at every = would break a value like http://x.com/?q=1. Always limit the split to the first separator. Trimming removes the spaces that people add around =.
/*
* Problem : Process lines.
* Input : Several lines.
* Output : One answer per query.
* Approach: Split at the first =.
* Time : O(n)
* Space : O(n)
* Java : 8 or newer.
*/
import java.util.Scanner;
public class Main {
// This method solves the task. It receives the input and returns the answer.
static String[] solve(String[] lines) {
// Step 1: Read the config lines until the line "---". Split each line at the FIRST "=" only.
java.util.Map<String, String> config = new java.util.HashMap<>();
int index = 0;
while (!lines[index].equals("---")) {
int equals = lines[index].indexOf('=');
String key = lines[index].substring(0, equals).trim();
String value = lines[index].substring(equals + 1).trim();
// Step 2: put replaces an old value, so the last value wins.
config.put(key, value);
index++;
}
// Step 3: The rest of the lines are queries. Answer each one.
String[] output = new String[lines.length - index - 1];
for (int i = index + 1; i < lines.length; i++) {
output[i - index - 1] = config.getOrDefault(lines[i], "missing");
}
return output;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
java.util.List<String> all = new java.util.ArrayList<>();
while (scanner.hasNextLine()) {
String line = scanner.nextLine().trim();
if (!line.isEmpty()) {
all.add(line);
}
}
String[] lines = all.toArray(new String[0]);
System.out.println(String.join("\n", solve(lines)));
}
}
Hints (1)
- Why split at only the first =?