[LeetCode] 20. Valid Parentheses

Joohyun·2021년 2월 9일

Algorithm

목록 보기
1/16
post-thumbnail

문제 링크

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

제출 코드

/**
 * @param {string} s
 * @return {boolean}
 */
var isValid = function(s) {
    const stack = []
    const pair = {
        '(' : ')',
        '{' : '}',
        '[' : ']'
    }
    for (i in s) {
         if (s[i] === pair[stack[stack.length-1]]) {
            stack.pop()
        } else {
            stack.push(s[i])
        }
    }
    return !stack.length
};

풀이 방법

주어진 문자열을 object로 만들어 놓은 뒤 loop을 돌면서 각각의 쌍을 체크하여 stack에 저장 (동일하면 pop, 다르면 push)

마지막까지 loop을 돈 뒤에 stack 안의 내용을 확인하여 남은 것이 있으면 false, 없으면 true를 return 한다.

profile
#Frontend Developer #Vue #Javascript #Typescript

0개의 댓글