1. Tokenize and Multi-Pass Reduction
Intuition
Split into tokens. In pass 1, resolve all * and / operations by splicing the array. In pass 2, resolve all remaining + and - operations.
Algorithm
- Step 1: Parse
sinto a token list of numbers and operators. - Step 2: Pass 1: find
*and/, compute with adjacent numbers, and replace with result. - Step 3: Pass 2: compute
+and-from left to right. - Step 4: Return final value.
#include <iostream>#include <string>#include <vector> class Solution {public: int calculate(std::string s) { std::vector<std::string> tokens; int n = s.length(); int i = 0; while (i < n) { if (s[i] == ' ') { i++; continue; } if (s[i] == '+' || s[i] == '-' || s[i] == '*' || s[i] == '/') { tokens.push_back(std::string(1, s[i])); i++; } else { std::string num = ""; while (i < n && s[i] >= '0' && s[i] <= '9') { num += s[i++]; } tokens.push_back(num); } } // Pass 1: * and / std::vector<std::string> pass1; for (size_t j = 0; j < tokens.size(); j++) { if (tokens[j] == "*" || tokens[j] == "/") { int left = std::stoi(pass1.back()); pass1.pop_back(); int right = std::stoi(tokens[j + 1]); int res = (tokens[j] == "*") ? (left * right) : (left / right); pass1.push_back(std::to_string(res)); j++; } else { pass1.push_back(tokens[j]); } } // Pass 2: + and - int result = std::stoi(pass1[0]); for (size_t j = 1; j < pass1.size(); j += 2) { int right = std::stoi(pass1[j + 1]); if (pass1[j] == "+") result += right; else if (pass1[j] == "-") result -= right; } return result; }}; int main() { Solution solver; std::cout << "Result: " << solver.calculate("3+5 / 2") << std::endl; return 0;}Time & Space Complexity
- Time complexity:
O(N^2)— Tokenize string into array, perform pass 1 evaluating all*and/(splicing array in O(N)), then pass 2 evaluating+and-. - Space complexity:
O(N)— O(N) space for tokens array.
Why Brute Force Doesn't Scale:
Unneeded heap allocations add memory overhead.
O(1) space evaluator processes 300,000 characters in <4ms with zero heap allocations.