- Decide the key that represents the information needed later.
- Update its count or stored state while scanning the input.
- Use constant-time expected lookups to detect matches or assemble the result.
Code notes
- 54 lines of Java from the credited upstream file 736.java.
- The implementation visibly relies on sequence storage, hash lookup, ordered lookup.
- 2 loop blocks detected.
Complexity
Expected hash operations are constant time, but the surrounding scan and the number of stored keys determine total work and memory.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution {2 public int evaluate(String expression) {3 return evaluate(expression, new HashMap<>());4 }5 6 private int evaluate(final String e, Map<String, Integer> prevScope) {7 if (Character.isDigit(e.charAt(0)) || e.charAt(0) == '-')8 return Integer.parseInt(e);9 if (prevScope.containsKey(e))10 return prevScope.get(e);11 12 Map<String, Integer> scope = new HashMap<>();13 scope.putAll(prevScope);14 15 final int spaceIndex = e.indexOf(' ');16 17 final String nextExpression = e.substring(spaceIndex + 1, e.length() - 1);18 List<String> tokens = split(nextExpression);19 20 if (e.startsWith("(m")) 21 return evaluate(tokens.get(0), scope) * evaluate(tokens.get(1), scope);22 if (e.startsWith("(a")) 23 return evaluate(tokens.get(0), scope) + evaluate(tokens.get(1), scope);24 25 26 for (int i = 0; i < tokens.size() - 2; i += 2)27 scope.put(tokens.get(i), evaluate(tokens.get(i + 1), scope));28 return evaluate(tokens.get(tokens.size() - 1), scope);29 }30 31 private List<String> split(final String s) {32 List<String> tokens = new ArrayList<>();33 StringBuilder sb = new StringBuilder();34 int opened = 0;35 36 for (char c : s.toCharArray()) {37 if (c == '(')38 ++opened;39 else if (c == ')')40 --opened;41 if (opened == 0 && c == ' ') {42 tokens.add(sb.toString());43 sb.setLength(0);44 } else {45 sb.append(c);46 }47 }48 49 if (sb.length() > 0)50 tokens.add(sb.toString());51 return tokens;52 }53}54