코딩테스트

[LeetCode/TS] 20. Valid Parentheses

다시은 2024. 12. 30. 21:38

문제

https://leetcode.com/problems/valid-parentheses/

 


 

1.

function isValid(s: string): boolean {
    const map = {
        ')': '(',
        '}': '{',
        ']': '['
    }
    const stack = [];

    for (let char of s) {
        if (char === '(' || char === '{' || char === '[') {
            stack.push(char);
        } else {
            const pop = stack.pop()
            const mappp = map[char]
            console.log({ pop, mappp })

            if (stack.length === 0 || mappp !== pop) {
                return false
            }
        }
    }

    return stack.length === 0;
};

 

 

 

문제점: 

예제 '()[]{}' 가 들어간다고 치면

1. '('
스택에 '(' 가 쌓인다.
stack (

2. ')'
else 구문으로 넘어가서

pop 변수에 값이 할당된다.
stack
그 후 if 조건으로 stack.length === 0 이 만족해버려서 false 라는 잘못된 값이 나온다.

 

 

해결책:
조건문에서 비교할 때 pop() 한다.

 

2.

function isValid(s: string): boolean {
    const map = {
        ')': '(',
        '}': '{',
        ']': '['
    }
    const stack = [];

    for (let char of s) {
        if (char === '(' || char === '{' || char === '[') {
            stack.push(char);
        } else {
            const mappp = map[char]
            if (stack.length === 0 || mappp !== stack.pop()) {
                return false
            }
        }
    }

    return stack.length === 0;
};

 

 

 

 

 

 

 

3. 다른 사람 풀이

function isValid(s: string): boolean {
    const stack = [];
    const p = { ')': '(', '}': '{', ']': '[' };
    for(let i = 0, len = s.length; i < len; i++) {
        if (['(', '[', '{'].includes(s[i])) {
            stack.push(s[i]);
            continue;
        } 
        
        if (stack.pop() !== p[s[i]]) {
            return false;
        }
    }
    return stack.length === 0;
};