20 · String Parsing & Expression Evaluation

#224 Basic Calculator

Hardsolve on LeetCode ↗

frequently reported atUberAmazonMicrosoftGoogleMetaBloomberg

the problem

In plain words

s is a valid expression with non-negative integers, '+', '-', brackets and spaces. A '-' can also mean "negative" at the very start or right after '(' — for example "-(2 + 3)" — but '+' is never used that way. Evaluate it without a built-in evaluator. Every number and every running total fits in a 32-bit int.

in s = "1 + 1"

out 2

in s = " 2-1 + 2 "

out 3

in s = "(1+(4+5+2)-3)+(6+8)"

out 23

(1 + 11 − 3) + 14 = 9 + 14.

  • 1 ≤ s.length ≤ 3·10⁵
  • s has digits, '+', '-', '(', ')' and ' '
  • s is valid; two operators never touch
  • Every number and running total fits in an int

your turn

Try it before you peek

Read the examples, say the brute force out loud, then write code: here or on LeetCode ↗. Stuck for 20 minutes? Open one hint at a time.

Solve it in the browser

LeetCode-style: complete the class. Compiled by the real javac (Java 17) and judged right here — nothing is sent anywhere.

    Solutions are hidden so you can try first. Even 20 minutes of real effort makes the answer stick far better than reading it.

    Marking the problem solved, or opening every hint, also shows it.

    practise next

    Similar problems

    1. #227
      Basic Calculator II
      Mediumin Parsing
    2. #394
      Decode String
      Mediumin Stacks
    3. #20
      Valid Parentheses
      Easyin Stacks