64일차 문제

양진혁·2022년 1월 5일
0

문제풀이

Write a function that takes a string of parentheses, and determines if the order of the parentheses is valid. The function should return true if the string is valid, and false if it's invalid.

Examples
"()" => true
")(()))" => false
"(" => false
"(())((()())())" => true

def valid_parentheses(string):
  el = []
  for i in string:
    if i == "(":
      el.append(i)
    elif i == ')':
            try:
                el.pop()
            except:
                return False
    if len(el) == 0:
        return True
    else:
        return False

빈 리스트에 반복문을 통해서 (가 있다면 추가해주고 만약 i가 )가 아니라면 False를 i가 )라고 한다면 리스트에서 마지막 인자를 지워주고 그게 빈 리스트일 경우 True를 아닐경우 False를 출력한다.

0개의 댓글