LC 20. Valid Parenttheses

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





评论和交流请发送邮件到 me@tianhegao.com





通过以下渠道赞赏此文