Code Kata(Python) week 2 - day 3

Jeongyun Heo·2021년 2월 3일
post-thumbnail

문제

s는 여러 괄호들로 이루어진 String 인자입니다.
s가 유효한 표현인지 아닌지 true/false로 반환해주세요.

종류는 '(', ')', '[', ']', '{', '}' 으로 총 6개 있습니다. 아래의 경우 유효합니다.

한 번 괄호를 시작했으면, 같은 괄호로 끝내야 한다.
괄호 순서가 맞아야 한다.

예를 들어 아래와 같습니다.

s = "()"
return true

s = "()[]{}"
return true

s = "(]"
return false

s = "([)]"
return false

s = "{[]}"
return true

문제풀이

def is_valid(string):
    couple = {):(,]:[,}:{}
    open = []
    for i in string:
        if i in couple:
            if [couple[i]] == open[-1:]:        # 공부,,
                open.pop()
            else:
                return False
        else:
            open.append(i)
    if open:                     # open에 값이 있다면 true, 없으면 false
        return False
    return True
def is_valid(string):
  check = []
  for s in string:
    if len(check) > 0:
      if s ==)and(== check[-1]:
        check.pop()
        continue
      if s ==]and[== check[-1]:
        check.pop()
        continue
      if s ==}and{== check[-1]:
        check.pop()
        continue
    if s in [(,{,[]:
      check.append(s)
    else:
      return False
  return True if len(check) == 0 else False

0개의 댓글