← 返回 meta 的题目列表Basic Calculator I / II
类型:qbank
LeetCode 224 / 227. Evaluate arithmetic expressions from a string. Stack-based evaluation with operator precedence; Meta-variant adds extra rules around eval order or unary operators.
Requirements
Parse and evaluate an arithmetic expression string with +, -, *, / and (LC 224) parentheses.
A recent phone-screen variant explicitly removes parentheses and focuses on operator precedence plus invalid-expression handling, e.g. strings shaped like 10/2+1*3+5.
Integer-only result; division truncates toward zero.
Single-pass stack solution: push numbers, hold a sign / pending operator; multiply/divide eagerly to respect precedence.
Examples
"3+2*2" → 7.
" 3/2 " → 1.
"(1+(4+5+2)-3)+(6+8)" → 23.
Notes
Meta variants add extra rules: unary minus inside parens, operator-precedence variants, sometimes an extra ^ for exponent.
Clarify the invalid-input contract before coding: return None, raise, or print an error. The phone-screen version leaves this open.
Common bug: mishandling multi-digit numbers — accumulate the digit until the next non-digit char.
A clean implementation uses one stack and a single sign carry, no recursion needed.
Preparation
Write LC 227 (no parens) from memory in <10 min.
Layer parens on top (LC 224) using recursion or an inner stack.
Practice the Meta-variant follow-ups: ^ precedence, -- unary, custom operator definitions.