孙晓聪
  • 最新
  • 博客
  • 书评
  • Valid Parentheses

    Description

    doc

    Solutions

    First Idea

    const validCloses = { ')': '(', '}': '{', ']': '[' }
    /**
     * @param {string} s
     * @return {boolean}
     */
    var isValid = function (s) {
      let stack = []
    
      for (let i = 0; i < s.length; i++) {
        const ch = s.charAt(i)
        const opening = validCloses[ch]
    
        if (!opening) {
          stack.push(ch)
          continue
        }
    
        const top = stack.pop()
        if (top !== opening) {
          return false
        }
      }
    
      return stack.length === 0
    }
    
    • Time Complexity: O(n)
    • Space Complexity: O(n)