[LeetCode] 20. Valid Parentheses (JavaScript)

nemo·2022년 5월 12일
0

문제

Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.

An input string is valid if:

Open brackets must be closed by the same type of brackets.
Open brackets must be closed in the correct order.

올바른 괄호인지 확인하고, 맞다면 true 아니면 false를 반환한다.

입력 예제

()[]{}

출력 예제

true




풀이

  • 열린 괄호라면 stack에 담는다.
  • 닫힌 괄호라면 map에서 stack의 맨 마지막 열린 괄호를 key로 갖는 value 값과 같은 지 확인하고 같다면 stack의 맨 마지막 괄호를 pop()하여 없앤다.
  • 마지막까지 stack에 하나라도 남아있다면, 짝이 없는 괄호이므로 false를 반환한다.
var isValid = function(s) {
  let answer = true;
  const map = {
    '(' : ')',
    '{' : '}',
    '[' : ']'
  };
  const stack = [];
  const open = Object.keys(map); // ["(", "{", "["]

  // 짝수가 아니면 리턴
  if (s.length % 2 !== 0) return false;

  for (let x of s) {
    // x가 열린 괄호인가? 그럼 스택에 넣는다.
    if(open.includes(x)) stack.push(x);
    else { // x는 닫힌 괄호
      // stack의 마지막 열린 괄호의 value와 x가 같다면
      // stack 마지막 열린 괄호 pop
      if (map[stack[stack.length - 1]] === x) stack.pop();
      else return false;
    }
  }

  return answer;
};


문제 출처
https://leetcode.com/problems/valid-parentheses/

0개의 댓글