You are given a string s representing a nested arithmetic expression.
The expression uses function-call syntax:
add(x, y)evaluates tox + y.sub(x, y)evaluates tox - y.
Each argument x or y is either an integer or another nested add/sub expression. The expression is guaranteed to be syntactically valid.
Return the integer value of the expression.
Examples
01 · Example 1
s = "add(1,sub(1,0))" return = 2
sub(1,0) = 1, then add(1,1) = 2.
02 · Example 2
s = "add(sub(5,2),sub(1,4))" return = 0
sub(5,2) = 3 and sub(1,4) = -3, so the result is 0.
03 · Example 3
s = "sub(add(7,8),sub(3,1))" return = 13
Constraints
1 <= s.length <= 2 * 10^5- Integer literals fit in a 32-bit signed integer.
- The input expression is valid and contains only
add,sub, integer literals, parentheses, commas, and optional spaces. - The final result fits in a 32-bit signed integer.
More Google problems
- Ad Rotation Scheduler With CooldownONSITE INTERVIEW · Seen Jul 2026
- Count Connected Point ClustersONSITE INTERVIEW · Seen Jul 2026
- Longest Target Run After ReplacementsONSITE INTERVIEW · Seen Jul 2026
- String Pattern ReplacementONSITE INTERVIEW · Seen Jul 2026
- Periodic Table Word FormationsPHONE SCREEN · Seen Jun 2026
- Split and Sort ArraySeen Jun 2026
- Fountain SafetyONSITE INTERVIEW · Seen Jun 2026
- Consolidate On-Call RotationsOA · Seen Jun 2026
public int evaluateExpression(String s) {
// write your code here
}
s"add(1,sub(1,0))"
expected2
checking account