268. Nesting

아현·2021년 8월 16일
0

Algorithm

목록 보기
280/400



1. JavaScript


정해


function solution(S) {
    // write your code in JavaScript (Node.js 8.9.4)
    let stack = [];
    
    for(let i=0; i<S.length; i++){
        if(S.charAt(i) == '('){
            stack.push(i);
        }
        if(S.charAt(i) == ')'){
            if(stack.length > 0){
                stack.pop();
            }
            else{
                return 0;
            }
        }
    }
    
    return stack.length == 0 ? 1 : 0
}


87%



// 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)
    const list = Array.from(S);
    let stack = [];

    for (char of list){
        if(char == '('){
            stack.push(char);
        }else if(stack.length == 0 || stack.pop() != '('){
            return 0
        }
    }

    return stack.length == 0 ? 1 : 0
}




2. Python



def solution(S):
    # write your code in Python 3.6
    
    if len(S) == 0: return 1
    if len(S) == 1: return 0

    stack = []
    
    for char in S:
        if char=="(":
            stack.append(char)
        else:
            if len(stack) > 0:
                stack.pop()
            else:
                return 0
                
    if len(stack) > 0: return 0
    return 1

profile
Studying Computer Science

0개의 댓글