알고리즘/Baekjoon
[CodingTest] 파이썬 백준 #4949 균형잡힌 세상
Happyoon ~
2021. 11. 29. 01:09
728x90
반응형
https://www.acmicpc.net/problem/4949
4949번: 균형잡힌 세상
하나 또는 여러줄에 걸쳐서 문자열이 주어진다. 각 문자열은 영문 알파벳, 공백, 소괄호("( )") 대괄호("[ ]")등으로 이루어져 있으며, 길이는 100글자보다 작거나 같다. 입력의 종료조건으로 맨 마
www.acmicpc.net
내 코드
while True:
line = input()
stack = []
if line=='.':
break;
flag =0
for item in line:
if item =='(':
stack.append(item)
elif item ==')':
if stack:
if stack[-1]=='(':
stack.pop()
else:
stack.append(item)
else:
print("no")
flag = 1
break
elif item =='[':
stack.append(item)
elif item ==']':
if stack:
if stack[-1]=='[':
stack.pop()
else:
stack.append(item)
else:
print("no")
flag = 1
break
if flag==0:
if stack:
print("no")
else :
print("yes")
문자열은 무시하고 괄호 짝만 조건을 설정했다.
다른 사람 코드
from sys import stdin, stdout
def isvalid(s):
stack = []
for c in s:
if c in '([':
stack.append(c)
elif c == ')':
if not stack or stack.pop() != '(':
return False
elif c == ']':
if not stack or stack.pop() != '[':
return False
return not stack
strings = stdin.readlines()
strings.pop()
for string in strings:
stdout.write("yes\n" if isvalid(string) else "no\n")
훨 짧다!! 함수를 사용했군 ..
반응형