본문 바로가기

Programmers

[프로그래머스] 올바른 괄호 (JS)

문제

https://school.programmers.co.kr/learn/courses/30/lessons/12909

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

코드

내 풀이

function solution(s){
    const stack = [];
    
    if(s.length%2===1) return false;
    
    for (e of s){
        if(stack.length===0 && e===')') return false;
        if(stack.length!==0 && stack[stack.length-1]==='(' && e===')') stack.pop();
        else stack.push(e);
    }
   
    return !stack.length;
}

 

다른 사람 풀이

function solution(s){
    let stackCount = 0;
    if(s.length%2===1) return false;
    for (let i = 0; i < s.length; i++) {
        stackCount += s[i] === '(' ? 1 : -1;
        if (stackCount < 0) return false;
    }
    return stackCount === 0 ? true : false;
}

 

정리

내가 처음 풀었을 때 효율성 테스트에서 통과를 하지 못해서 다음과 같은 조건을 넣어주니 해결되었다.

function solution(s){
    ...
    
    if(s.length%2===1) return false;
    
    for (e of s){
        if(stack.length===0 && e===')') return false;
        ...
    }
   
    ...
}

 

다른 사람 풀이를 보니 스택 array를 만들어서 추가하고 삭제하는 것보다 숫자 변수 하나 둬서 그 변수가 음수일 때 false를 리턴하는 방식으로 하는 게 더 효율적인 것 같다.

참조

https://jsikim1.tistory.com/251