20. Valid Parentheses

llsh·2021년 12월 12일
0

리트코드

목록 보기
7/7

문제 설명

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

Example 1:

Input: s = "()"
Output: true

Example 2:

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

Example 3:

Input: s = "(]"
Output: false

Example 4:

Input: s = "([)]"
Output: false

Example 5:

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

Solution

var isValid = function(s) {
  let test = []
  const list= {
      "}" : "{",
      "]" : "[",
      ")" : "("
  };
  for(const x of s){
    if(test.length === 0) test.push(x)
    else if (test[test.length-1] === list[x]) test.pop()
    else test.push(x)
  }
    return test.length === 0
};
profile
기록 기록 기록..

0개의 댓글