- 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 C++ from the credited upstream file 736.cpp.
- The implementation visibly relies on sequence storage, hash 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:3 int evaluate(string expression) {4 return evaluate(expression, unordered_map<string, int>());5 }6 7 private:8 int evaluate(const string& e, unordered_map<string, int> scope) {9 if (isdigit(e[0]) || e[0] == '-')10 return stoi(e);11 if (const auto it = scope.find(e); it != scope.cend())12 return it->second;13 14 const int spaceIndex = e.find_first_of(' ');15 const string nextExpression =16 e.substr(spaceIndex + 1, e.length() - spaceIndex - 2); 17 const vector<string> tokens = split(nextExpression);18 19 20 if (e[1] == 'm') 21 return evaluate(tokens[0], scope) * evaluate(tokens[1], scope);22 if (e[1] == 'a') 23 return evaluate(tokens[0], scope) + evaluate(tokens[1], scope);24 25 26 for (int i = 0; i + 1 < tokens.size(); i += 2)27 scope[tokens[i]] = evaluate(tokens[i + 1], scope);28 return evaluate(tokens.back(), scope);29 };30 31 vector<string> split(const string& e) {32 vector<string> tokens;33 string s;34 int opened = 0;35 36 for (const char c : e) {37 if (c == '(')38 ++opened;39 else if (c == ')')40 --opened;41 if (opened == 0 && c == ' ') {42 tokens.push_back(s);43 s = "";44 } else {45 s += c;46 }47 }48 49 if (!s.empty())50 tokens.push_back(s);51 return tokens;52 }53};54