|
| 1 | +// Time: O(n) |
| 2 | +// Space: O(n) |
| 3 | + |
| 4 | +// Support +, -, *, /. |
| 5 | +class Solution { |
| 6 | +public: |
| 7 | + Node* expTree(string s) { |
| 8 | + static const unordered_map<char, int> precedence = {{'+', 0}, {'-', 0}, {'*', 1}, {'/', 1}}; |
| 9 | + |
| 10 | + stack<Node *> operands; |
| 11 | + stack<char> operators; |
| 12 | + int64_t operand = 0; |
| 13 | + for (int i = 0; i < size(s); ++i) { |
| 14 | + if (isdigit(s[i])) { |
| 15 | + operand = operand * 10 + s[i] - '0'; |
| 16 | + if (i + 1 == size(s) || !isdigit(s[i + 1])) { |
| 17 | + operands.emplace(new Node(operand + '0')); |
| 18 | + operand = 0; |
| 19 | + } |
| 20 | + } else if (s[i] == '(') { |
| 21 | + operators.emplace(s[i]); |
| 22 | + } else if (s[i] == ')') { |
| 23 | + while (!empty(operators) && operators.top() != '(') { |
| 24 | + compute(&operands, &operators); |
| 25 | + } |
| 26 | + operators.pop(); |
| 27 | + } else if (precedence.count(s[i])) { |
| 28 | + while (!empty(operators) && precedence.count(operators.top()) && |
| 29 | + precedence.at(operators.top()) >= precedence.at(s[i])) { |
| 30 | + compute(&operands, &operators); |
| 31 | + } |
| 32 | + operators.emplace(s[i]); |
| 33 | + } |
| 34 | + } |
| 35 | + while (!empty(operators)) { |
| 36 | + compute(&operands, &operators); |
| 37 | + } |
| 38 | + return operands.top(); |
| 39 | + } |
| 40 | + |
| 41 | +private: |
| 42 | + template<typename T> |
| 43 | + void compute(stack<T> *operands, stack<char> *operators) { |
| 44 | + const auto right = operands->top(); operands->pop(); |
| 45 | + const auto left = operands->top(); operands->pop(); |
| 46 | + const char op = operators->top(); operators->pop(); |
| 47 | + operands->emplace(new Node(op, left, right)); |
| 48 | + } |
| 49 | +}; |
0 commit comments