https://www.hackerrank.com/interview/interview-preparation-kit/stacks-queues/challenges
level2
#!/bin/python3
import math
import os
import random
import re
import sys
# Complete the isBalanced function below.
def isBalanced(s):
front = ["{", "[", "("]
end = ["}", "]", ")"]
dict = {
front[0] : end[0],
front[1] : end[1],
front[2] : end[2],
}
stack = []
for item in s:
if len(stack) == 0:
stack.append(item)
continue
top = stack.pop()
try:
if dict[top] == item:
continue
else:
stack.append(top)
stack.append(item)
except KeyError:
return "NO"
if not stack:
return "YES"
else:
return "NO"
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
t = int(input())
for t_itr in range(t):
s = input()
result = isBalanced(s)
fptr.write(result + '\n')
fptr.close()
'algorithm > python' 카테고리의 다른 글
프로그래머스/DFS,BFS/타겟 넘버 (0) | 2020.03.18 |
---|---|
프로그래머스/탐욕법/체육복 (0) | 2020.03.16 |
hackerrank/Hash Tables/Ransom Note (0) | 2020.03.09 |
hackerrank/String/Sherlock and the Valid String (0) | 2020.03.08 |
프로그래머스/완전탐색/모의고사 (0) | 2020.03.08 |