LeetCode - Valid Parentheses

wanderer-s·2021년 12월 20일
0

Algorithm

목록 보기
4/19
post-thumbnail

Problem

Valid Parentheses
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

JavaScript

/**
 * @param {string} s
 * @return {boolean}
 */
var isValid = function(s) {
    const brakets = {
        ')': '(',
        '}': '{',
        ']': '['
    }
    const arr = []
    for(let idx in s) {
        const char = s[idx]
        if(char === '(' || char === '{' || char === '[') {
            arr.push(char)
        } else {
            if(arr[arr.length - 1] === brakets[char]) {
                arr.pop();
            } else return false
        }
    }
    return arr.length === 0
};

Feedback은 언제나 환영입니다🤗

profile
You only get one life. It's actually your duty to live it as fully as possible.

0개의 댓글