일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
Tags
- 715. Range Module
- kaggle
- concurrency
- 파이썬
- Convert Sorted List to Binary Search Tree
- 시바견
- 315. Count of Smaller Numbers After Self
- 프로그래머스
- Regular Expression
- Class
- Python Implementation
- t1
- shiba
- Generator
- Substring with Concatenation of All Words
- 밴픽
- 109. Convert Sorted List to Binary Search Tree
- Python
- data science
- attribute
- 운영체제
- DWG
- iterator
- Protocol
- 30. Substring with Concatenation of All Words
- 43. Multiply Strings
- LeetCode
- Python Code
- 컴퓨터의 구조
- Decorator
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 |