728x90
class ArrayStack:
def __init__(self):
self.data = []
def size(self):
return len(self.data)
def isEmpty(self):
return self.size() == 0
def push(self, item):
self.data.append(item)
def pop(self):
return self.data.pop()
def peek(self):
return self.data[-1]
prec = {
'*': 3, '/': 3,
'+': 2, '-': 2,
'(': 1
}
def solution(s):
opStack = ArrayStack()
answer = ""
for op in s:
# 닫는 괄호를 만나는 경우
if op == ")":
# 여는 괄호를 만날 때까지 pop
while opStack.peek() != "(":
answer += opStack.pop()
# 스택에 있는 여는 괄호 pop
opStack.pop()
# 연산자들이 아닌 경우
elif op not in prec:
answer += op
else:
# 스택이 비어있는 경우
if opStack.isEmpty():
opStack.push(op)
# 스택에 연산자들이 있는 경우
else:
# 현재의 연산자의 우선 순위가 더 큰 경우
if prec[opStack.peek()] < prec[op] or op == "(":
opStack.push(op)
# 현재의 연산자의 우선 순위가 더 작은 경우
else:
# 스택에 있는 연산자들 중 현재의 연산자보다 우선 순위가 더 큰 경우 모두 pop
while not opStack.isEmpty():
if prec[opStack.peek()] >= prec[op]:
answer += opStack.pop()
else:
break
opStack.push(op)
while not opStack.isEmpty():
answer += opStack.pop()
return answer
출처: airvw.github.io/datastructure/2020-12-07-prefix-to-postfix/
스택 문제에서 매번 틀리는 부분:
스택이 비었을때 채워주기
큰 분기가 무엇인지 항상 생각하기
728x90
'DC 2' 카테고리의 다른 글
[자료구조] 대중소 괄호 짝 맞추기 파이썬 (stack, valid parentheses) (0) | 2021.04.22 |
---|---|
[자료구조] 좌석구매 파이썬 (hashable VS. unhashable) (0) | 2021.04.22 |
[자료구조] 사탕 담기 파이썬 (0) | 2021.04.20 |
[자료구조] 카펫 파이썬 (0) | 2021.04.20 |
[자료구조] 운송 트럭 파이썬 (dict) (0) | 2021.04.20 |
댓글