- 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
- 45 lines of C++ from the credited upstream file evaluate-valid-expressions.cpp.
- The implementation visibly relies on sequence storage, hash lookup.
- 1 loop block 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.
123 45class Solution {6public:7 long long evaluateExpression(string expression) {8 static const unordered_map<string, function<int64_t (int64_t, int64_t)>> LOOKUP = {9 {"add", [](int64_t a, int64_t b) { return a + b; }},10 {"sub", [](int64_t a, int64_t b) { return a - b; }},11 {"mul", [](int64_t a, int64_t b) { return a * b; }},12 {"div", [](int64_t a, int64_t b) { return a / b; }}13 };14 15 static const string SYMBOLS = "(,)";16 17 string curr;18 vector<string> ops;19 vector<vector<int64_t>> params(1);20 for (const auto& x : expression) {21 if (SYMBOLS.find(x) == string::npos) {22 curr.push_back(x);23 continue;24 }25 if (x == '(') {26 ops.emplace_back(curr);27 curr.clear();28 params.emplace_back();29 continue;30 }31 if (!empty(curr)) {32 params.back().emplace_back(stoll(curr));33 curr.clear();34 }35 if (x != ')') {36 continue;37 }38 const auto op = ops.back(); ops.pop_back();39 const auto param = params.back(); params.pop_back();40 params.back().emplace_back(LOOKUP.at(op)(param[0], param[1]));41 }42 return !empty(params[0]) ? params[0][0] : stoll(curr);43 }44};45