Payments app~30 min2s · 256 MBtarget O(n) time, O(n) spaceclassic twin: lc-224stacks
A payments app lets a merchant define a fee formula. The formula uses whole numbers, the signs + and -, brackets, and spaces. A refund rule can start with a minus sign, as in -(2 + 3), or have one right after an opening bracket, as in (-4 + 9).
The app must compute the value of a formula. A formula can have up to 100,000 characters.
Write evaluate_bracketed(expression).
expression is valid. It holds whole numbers that are 0 or more, +, -, (, ) and spaces. A - may also be a sign: at the very start, or right after a (. There is no other sign in front of a number.- in front of a bracket flips the sign of everything inside it. The value of the formula, and of every group in it, fits in a 32-bit signed integer.Input: expression = "8 - (3 - (2 + 1)) + (-4 + 9)"
Output: 13Keep the value of the group you are in, and the sign of what comes next. When a ( opens a group, save that value and the sign in front of the bracket on a stack, and start the group at 0. When a ) closes it, add its value to the saved one, with the saved sign.
| Character | Number finished | Result after | Sign after | Stack of (result, sign) after |
|---|---|---|---|---|
- |
8 | 8 | -1 | (empty) |
( |
0 | 0 | +1 | (8, -1) |
- |
3 | 3 | -1 | (8, -1) |
( |
0 | 0 | +1 | (8, -1), (3, -1) |
+ |
2 | 2 | +1 | (8, -1), (3, -1) |
) |
1 | 0 | +1 | (8, -1) |
) |
0 | 8 | +1 | (empty) |
+ |
0 | 8 | +1 | (empty) |
( |
0 | 0 | +1 | (8, +1) |
- |
0 | 0 | -1 | (8, +1) |
+ |
4 | -4 | +1 | (8, +1) |
) |
9 | 13 | +1 | (empty) |
| (end) | 0 | 13 | +1 | (empty) |
The value is 13. The group (2 + 1) is 3, the group around it is 3 - 3 = 0, so 8 - 0 = 8, and the last group (-4 + 9) is 5.
Input: expression = "-(4 - 9) + 1"
Output: 6The group (4 - 9) is -5. The minus sign in front of it flips it to 5, and then 1 is added: 6.
Input: expression = "(7)"
Output: 7A bracket around a single number does not change its value.
1 ≤ length of expression ≤ 10^5(A plan that evaluates one group and then rescans the text for the next one costs about n^2 / 16 steps when many groups stand side by side. That is 6 × 10^8 steps for 100,000 characters, which is too slow.
A plan that calls itself for every bracket can nest 33,000 calls deep. That can overflow the call stack, so the stack of saved values should be your own.