[LeetCode]20. Valid Parentheses - JavaScript

롱롱·2022년 8월 20일
0

LeetCode 문제풀이

목록 보기
5/5

LeetCode에서 풀어보기

👀 Problem

Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
An input string is valid if:
1. Open brackets must be closed by the same type of brackets.
2. Open brackets must be closed in the correct order.

Example 1

Input: s = "()"
Output: true

Example 2

Input: s = "()[]{}"
Output: true

Example 3

Input: s = "(]"
Output: false

Constraints

  • 1 <= s.length <= 104
  • s consists of parentheses only '()[]{}'.

✔ Solution

var isValid = function(s) {
    let stack = [];
    const map = {
        '(' : ')',
        '{' : '}',
        '[' : ']'     
    };
    for (let i = 0 ; i < s.length; i++) {
        if (s[i] === '(' || s[i] === '{' || s[i] === "[") {
            stack.push(s[i]);
        } else {
            if (map[stack[stack.length - 1]] === s[i]) {
                stack.pop();                
            } else return false;
        }
    }
    return stack.length === 0;
};

자료구조 공부를 하며 비슷한 문제를 풀어봐서 접근하기 수월했다. 괄호 끼리의 짝이 있고 순서가 중요하기 때문에 stack을 통해 쉽게 풀 수 있는 문제였다. 괄호끼리의 짝을 map 객체에 넣어 논 후 여는 괄호이면 스택에 push하고 닫는 괄호라면 괄호에 맞는 짝인지를 map 객체에서 불러와 비교하고 최종적으로 스택의 length가 0이라면 true를 아니라면 false를 return하였다.

profile
개발자를 꿈꾸며 공부중입니다.

0개의 댓글