s는 여러 괄호들로 이루어진 String 인자입니다. s가 유효한 표현인지 아닌지 true/false로 반환해주세요. 종류는 '(', ')', '[', ']', '{', '}' 으로 총 6개 있습니다. 아래의 경우 유효합니다. 한 번 괄호를 시작했으면, 같은 괄호로 끝내야 한다. 괄호 순서가 맞아야 한다.
by 예랑님.
def is_valid(string):
my_list = ["()", "[]", "{}"]
while "()" in string or "[]" in string or "{}" in string:
for gwal in my_list:
print(gwal)
if gwal in string:
string = string.replace(gwal, "")
if len(string) == 0 :
return True
return False
result = is_valid("(()[]{}]")
print(result)
by 지우님.
def is_valid(string):
str_list = []
dic = {')' : '(', ']', '[', '}', '{'}
for i in s:
if i in {'(', '{', '['}:
str_list.append(i)
else:
if not str_list or dic[i] != str_list.pop():
return False
return not str_list
by ??
def is_valid(string):
a = '()'
b = '{}'
c = '[]'
while string:
if a in string :
string = string.replace(a, '')
elif b in string :
string = string.replace(b, '')
elif c in string :
string = string.replace(c, '')
else:
return False
return True