algorithm/python

hackerrank/Stacks and Queues/Balanced Brackets

아르르르를를르 2020. 3. 9. 20:41

https://www.hackerrank.com/interview/interview-preparation-kit/stacks-queues/challenges

level2

 

#!/bin/python3

import math
import os
import random
import re
import sys

# Complete the isBalanced function below.
def isBalanced(s):
    front = ["{", "[", "("]
    end = ["}", "]", ")"]

    dict = {
        front[0] : end[0],
        front[1] : end[1],
        front[2] : end[2],
    }

    stack = []
    for item in s:
        if len(stack) == 0:
            stack.append(item)
            continue
        top = stack.pop()
        try:
            if dict[top] == item:
                continue
            else:
                stack.append(top)
                stack.append(item)
        except KeyError:
            return "NO"
    if not stack:
        return "YES"
    else:
        return "NO"

if __name__ == '__main__':
    fptr = open(os.environ['OUTPUT_PATH'], 'w')

    t = int(input())

    for t_itr in range(t):
        s = input()

        result = isBalanced(s)

        fptr.write(result + '\n')

    fptr.close()