Then, compute the addition on the right: add(1,1) = 1 + 1 = 2
Finally, divide the two main results: div(16,2) = 16 / 2 = 8
Therefore, the entire expression evaluates to 8.
Constraints:
1 <= expression.length <= 105
expression is valid and consists of digits, commas, parentheses, the minus sign '-', and the lowercase strings "add", "sub", "mul", "div".
All intermediate results fit within the range of a long integer.
All divisions result in integer values.
Solutions
Solution 1: Recursion
Thinking
The expression is a nested \(\mathrm{op}(a,b)\) whose shape is given by parentheses, so recursive descent fits. At the current index we either parse a literal, or read an operator, recurse on the two operands, and apply \(\mathrm{add}/\mathrm{sub}/\mathrm{mul}/\mathrm{div}\).
We define a recursive function \(\text{parse}(i)\) to parse the subexpression starting from index \(i\) and return the computed result along with the next unprocessed index position. The answer is \(\text{parse}(0)[0]\).
The implementation of the function \(\text{parse}(i)\) is as follows:
If the current position \(i\) is a digit or a negative sign -, continue scanning forward until a non-digit character is encountered, parse an integer, and return that integer along with the next unprocessed index position.
Otherwise, the current position \(i\) is the starting position of an operator op. We continue scanning forward until we encounter a left parenthesis (, parsing the operator string op. Then we skip the left parenthesis, recursively call \(\text{parse}\) to parse the first parameter \(a\), skip the comma, recursively call \(\text{parse}\) to parse the second parameter \(b\), and finally skip the right parenthesis ).
Based on the operator op, calculate the result of \(a\) and \(b\), and return that result along with the next unprocessed index position.
The time complexity is \(O(n)\) and the space complexity is \(O(n)\), where \(n\) is the length of the expression string.