[Leetcode - Algorithm] Valid Parentheses

3762 ワード

Question



かっこが一致しているかどうかを確認します.

Answer

var isValid = function(s) {
    
   let bracket = {
       "(" : ")",
       "{" : "}",
       "[" : "]",
   }
    
   let heap = [];
    
    for(let char of s){
        if(bracket[char]){    // bracket[char] 가 "("
            heap.push(bracket[char]);  // => heap = [")"]  => loop 종료
        }else{  // bracket[char] === ")" 일때 pop 해서 나오는 ")" 가 맞는지 확인.
            if(heap.pop() !== char) return false; 
        }
    }
    return (!heap.length); 
};

実行結果値


Runtime: 72 ms, faster than 95.80% of JavaScript online submissions for Valid Parentheses.
Memory Usage: 38.9 MB, less than 53.24% of JavaScript online submissions for Valid Parentheses.