practivceAlgorithm/swexpertacademy

[SWEA][Python] 4866 괄호검사

findTheValue 2021. 8. 15. 18:44

stack써서 푸는 문제. stack하나로도 가능한데..

 

def bracket_inspection(s):
    dic = {')':0, '}':0,']':0, '(':0, '{':0,'[':0}
    stack1 = []
    stack2 = []
    for chr in s:
        if chr in dic:
            dic[chr] += 1
            stack1.append(chr)

    if dic[')'] != dic['('] or dic['}'] != dic['{'] or dic[']'] != dic['[']:
        return 0

    while stack1:
        check = stack1.pop()
        if check == ')' or check == '}' or check==']':
            stack2.append(check)
        else:
            if check =='(':
                if stack2[-1]==')':
                    stack2.pop()
                else:
                    return 0
            elif check=='{':
                if stack2[-1]=='}':
                    stack2.pop() 
                else:
                    return 0
            elif check=='[':
                if stack2[-1]==']':
                    stack2.pop()
                else:
                    return 0
        
    return 1