Tianhe Gao

LC 20. Valid Parenttheses

 1/**
 2 * @param {string} s
 3 * @return {boolean}
 4 */
 5var isValid = function(s) {
 6  const n = s.length
 7  if (n % 2 === 1) return false
 8  const pairs = new Map([
 9    [')', '('],
10    [']', '['],
11    ['}', '{']
12  ])
13  const stk = []
14  for (let ch of s) {
15    if (pairs.has(ch)) {
16      if (!stk.length || stk[stk.length - 1] !== pairs.get(ch)) return false
17      stk.pop()
18    } else {
19      stk.push(ch)
20    }
21  }
22  return !stk.length
23};

No notes link to this note

Welcome to tell me your thoughts via "email"
UP