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().
def calculate(self, s):
res, num, sign, stack = 0, 0, 1, []
for ss in s:
if ss.isdigit():
num = 10*num + int(ss)
elif ss in ["-", "+"]:
res += sign*num
num = 0
sign = [-1, 1][ss=="+"]
elif ss == "(":
stack.append(res)
stack.append(sign)
sign, res = 1, 0
elif ss == ")":
res += sign*num
res *= stack.pop()
res += stack.pop()
num = 0
return res + num*sign
Related Problems
Given an array of meeting time intervals intervals where intervals[i] = [starti, endi], return the minimum number of conference rooms required.
Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.
Implement the MinStack class:
MinStack() initializes the stack object.
void push(int val) pushes the element val onto the stack.
void pop() removes the element on the top of the stack.
int top() gets the top element of the stack.
int getMin() retrieves the minimum element in the stack.
You must implement a solution with O(1) time complexity for each function.
Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
Given an integer array nums and an integer k, return the k most frequent elements. You may return the answer in any order.