일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | |||
5 | 6 | 7 | 8 | 9 | 10 | 11 |
12 | 13 | 14 | 15 | 16 | 17 | 18 |
19 | 20 | 21 | 22 | 23 | 24 | 25 |
26 | 27 | 28 | 29 | 30 | 31 |
Tags
- LeetCode
- Python
- Convert Sorted List to Binary Search Tree
- Python Implementation
- data science
- 시바견
- 파이썬
- 109. Convert Sorted List to Binary Search Tree
- Protocol
- Generator
- t1
- shiba
- 컴퓨터의 구조
- iterator
- Class
- kaggle
- 715. Range Module
- Python Code
- Substring with Concatenation of All Words
- 운영체제
- 프로그래머스
- attribute
- Decorator
- 30. Substring with Concatenation of All Words
- DWG
- 43. Multiply Strings
- concurrency
- 밴픽
- 315. Count of Smaller Numbers After Self
- Regular Expression
Archives
- Today
- Total
Scribbling
LeetCode: 772. Basic Calculator III 본문
class Solution:
def calculate(self, s: str) -> int:
# ' ' is intentionally added,
# to mark the end of the given string s
# encountering ' ' will add the last number to the stack
self.s = s + ' '
self.ptr = 0
return self.calc()
def calc(self):
num, stack, sign = 0, [], '+'
while self.ptr < len(self.s):
c = self.s[self.ptr]
# if met with '(',
# get the evaluated number by recursion
if c == '(':
self.ptr += 1
num = self.calc()
# deal with digits
elif c.isdigit():
num = num * 10 + int(c)
self.ptr += 1
# if met with operators or ')' or ' ',
else:
# if met with operators,
# stack the number and update sign & num
if sign == '+':
stack.append(num)
elif sign == '-':
stack.append(-num)
elif sign == '*':
stack.append(stack.pop()*num)
elif sign == '/':
stack.append(int(stack.pop()/num))
# if met with ')',
# stack the number and return sum(stack)
if c == ')':
self.ptr += 1
return sum(stack)
sign = c
num = 0
self.ptr += 1
return sum(stack)
'Computer Science > Coding Test' 카테고리의 다른 글
LeetCode: 715. Range Module (0) | 2022.03.18 |
---|---|
LeetCode: 833. Find And Replace in String (0) | 2022.03.15 |
LeetCode: 745. Prefix and Suffix Search (0) | 2022.03.10 |
LeetCode: 1834. Single-Threaded CPU (0) | 2022.03.08 |
LeetCode: 407. Trapping Rain Water II (0) | 2022.03.08 |