Skip to content

Commit 7dea473

Browse files
parksbootony9402
andauthored
[ADD] baekjoon 1918 python solution (#97)
* ADD 1918.py * fix typo and refactoring --------- Co-authored-by: Minsang Kim <[email protected]>
1 parent 6665b3b commit 7dea473

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed

solutions/baekjoon/1918/main.py

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
# Authored by : parksb08
2+
# Co-authored by : -
3+
# Link : http://boj.kr/467d3ad526dc460db851f8774d4f86b7
4+
import sys
5+
def input():
6+
return sys.stdin.readline().rstrip()
7+
8+
inputs = input()
9+
rs=[]
10+
stack=[]
11+
i_p={'+':1,'-':1,'*':2,'/':2, '(':4, ')':0} #stack에 들어갈 때
12+
s_p={'+':1,'-':1,'*':2,'/':2, '(':0} #stack에서 나올 때
13+
for i in inputs:
14+
if i.isalpha():
15+
rs.append(i)
16+
elif i == '(':
17+
stack.append(i)
18+
elif i ==')':
19+
while stack and s_p[stack[-1]] >= i_p[i]:
20+
if stack[-1]=='(':
21+
stack.pop()
22+
break
23+
else:
24+
rs.append(stack.pop())
25+
else:
26+
while stack and s_p[stack[-1]] >= i_p[i]:
27+
rs.append(stack.pop())
28+
stack.append(i)
29+
while stack:
30+
rs.append(stack.pop())
31+
32+
print(''.join(rs))
33+
34+
''' Solution Description
35+
후위표기식을 만드는 문제
36+
스택을 이용해서 풀었다.
37+
1. 알파벳이면 결과에 바로 추가
38+
2. 여는 괄호면 스택에 추가
39+
3. 닫는 괄호면 여는 괄호가 나올 때 까지 스택에서 pop
40+
4. 연산자면 스택에서 우선순위가 높은 연산자가 나올 때 까지 pop
41+
5. 스택이 빌 때 까지 pop
42+
6. 결과 출력
43+
'''

0 commit comments

Comments
 (0)