返回题库

基础计算器

Basic Calculator

专题
Algorithmic Programming / 算法编程
难度
L4
来源
Citadel

题目详情

问题:基础计算器

考察:字符串、栈

来源:Citadel

链接:https://www.jointaro.com/interviews/questions/basic-calculator/

Given a string s representing a valid expression, implement a basic calculator to evaluate it, and return the result of the evaluation.

Note: You are not allowed to use any built-in function which evaluates strings as mathematical expressions, such as eval().

 

Example 1:

Input: s = "1 + 1"
Output: 2

Example 2:

Input: s = " 2-1 + 2 "
Output: 3

Example 3:

Input: s = "(1+(4+5+2)-3)+(6+8)"
Output: 23

 

Constraints:

  • 1 <= s.length <= 3 * 105
  • s consists of digits, '+', '-', '(', ')', and ' '.
  • s represents a valid expression.
  • '+' is not used as a unary operation (i.e., "+1" and "+(2 + 3)" is invalid).
  • '-' could be used as a unary operation (i.e., "-1" and "-(2 + 3)" is valid).
  • There will be no two consecutive operators in the input.
  • Every number and running calculation will fit in a signed 32-bit integer.
解析

思路:扫描表达式并维护当前数、符号和累计结果。遇到左括号时把当前结果和符号压栈,重新计算括号内部;遇到右括号时把括号结果乘以前一层符号再加回上一层结果。

复杂度:单次扫描 O(n),括号栈空间 O(n)。