Optional Chain: City Lookup
Problem
Commands: put ID CITY stores a city for an id (the city - means no city; a new put replaces the old one) and get ID prints the city in capital letters. If the id is not known or has no city, print unknown.
Constraints
- 1 <= commands <= 100
- ID and CITY have no spaces
Examples
Input
put u1 pune get u1 get u2
Output
PUNE unknown
Solutions
Each step that can fail gets its own if. It works in all versions, but the real rule (a city, not blank, in capital letters, else unknown) is spread over the branches.
/*
* Problem : Look up the city.
* Input : Command lines.
* Output : One line per get.
* Approach: Null checks
* 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: Without Optional: check for a missing key and for the "-" mark one by one.
java.util.Map<String, String> cities = new java.util.HashMap<String, String>();
java.util.List<String> out = new java.util.ArrayList<String>();
for (String line : lines) {
String[] part = line.split(" ");
if (part[0].equals("put")) {
cities.put(part[1], part[2]);
} else {
String city = cities.get(part[1]);
if (city != null && !city.equals("-")) {
out.add(city.toUpperCase());
} else {
out.add("unknown");
}
}
}
return out.toArray(new String[0]);
}
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)
- What are the two reasons for unknown?