266. Brackets

아현·2021년 8월 15일
0

Algorithm

목록 보기
278/400
post-thumbnail
post-custom-banner



1. JavaScript


// you can write to stdout for debugging purposes, e.g.
// console.log('this is a debug message');

function solution(S) {
    // write your code in JavaScript (Node.js 8.9.4)

    if(S.length == 0){
        return 1
    }

    let bracket = {
        ')': '(',
        '}': '{',
        ']': '['
    }
    let stack = [];
    let list = Array.from(S);
    
    for(c of list){
        if(!bracket.hasOwnProperty(c)){
            stack.push(c);
        }else if(stack.length == 0 || bracket[c] != stack.pop()){
            return 0
        }
    }

    if(stack.length == 0){
        return 1
    }else{
        return 0
    }

    
}



2. Python


# you can write to stdout for debugging purposes, e.g.
# print("this is a debug message")

def solution(S):

    if len(S) == 0 :
        return 1

    stack = []
    bracket = {
            ')': '(',
            '}': '{',
            ']': '['
        }

    for char in S:
        if char not in bracket:
            stack.append(char)
        elif not stack or bracket[char] != stack.pop():
            return 0

    if len(stack) == 0:
        return 1
    else:
        return 0
    

 
profile
For the sake of someone who studies computer science
post-custom-banner

0개의 댓글