Basic Calculator II
LeetCode 227 | Difficulty: Mediumβ
MediumProblem Descriptionβ
Given a string s which represents an expression, evaluate this expression and return its value.
The integer division should truncate toward zero.
You may assume that the given expression is always valid. All intermediate results will be in the range of [-2^31, 2^31 - 1].
Note: You are not allowed to use any built-in function which evaluates strings as mathematical expressions, such as eval().
Example 1:
Input: s = "3+2*2"
Output: 7
Example 2:
Input: s = " 3/2 "
Output: 1
Example 3:
Input: s = " 3+5 / 2 "
Output: 5
Constraints:
- `1 <= s.length <= 3 * 10^5`
- `s` consists of integers and operators `('+', '-', '*', '/')` separated by some number of spaces.
- `s` represents **a valid expression**.
- All the integers in the expression are non-negative integers in the range `[0, 2^31 - 1]`.
- The answer is **guaranteed** to fit in a **32-bit integer**.
Topics: Math, String, Stack
Approachβ
Stackβ
Use a stack (LIFO) to track elements that need future processing. Process elements when a "trigger" condition is met (e.g., finding a smaller/larger element). Monotonic stack maintains elements in sorted order for next greater/smaller element problems.
Matching brackets, next greater element, evaluating expressions, backtracking history.
Mathematicalβ
Look for mathematical patterns or formulas. Consider: modular arithmetic, GCD/LCM, prime factorization, combinatorics, or geometric properties.
Problems with clear mathematical structure, counting, number properties.
String Processingβ
Consider character frequency counts, two-pointer approaches, or building strings efficiently. For pattern matching, think about KMP or rolling hash. For palindromes, expand from center or use DP.
Anagram detection, palindrome checking, string transformation, pattern matching.
Solutionsβ
Solution 1: C# (Best: 121 ms)β
| Metric | Value |
|---|---|
| Runtime | 121 ms |
| Memory | 37.6 MB |
| Date | 2022-01-24 |
public class Solution {
public int Calculate(string s) {
Stack<int> st = new Stack<int>();
int current = 0; char sign = '+';
for (int i = 0; i < s.Length; i++)
{
char c = s[i];
if(char.IsDigit(c))
{
current = current*10 + (c-'0');
}
if((!char.IsDigit(c) && c != ' ') || i==s.Length-1)
{
if(sign == '+') st.Push(current);
if(sign == '-') st.Push(-current);
if(sign == '*') st.Push(st.Pop()*current);
if(sign=='/') st.Push(st.Pop()/current);
sign = c;
current = 0;
}
}
return st.Sum();
}
}
Complexity Analysisβ
| Approach | Time | Space |
|---|---|---|
| Stack | $O(n)$ | $O(n)$ |
Interview Tipsβ
- Discuss the brute force approach first, then optimize. Explain your thought process.
- Think about what triggers a pop: is it finding a match, or finding a smaller/larger element?