skip to content

LeetCode
LeetCode 020 有效的括号

[数据结构]Stack.js
class Stack extends Array {
  peek() {
    return this[this.length - 1]
  }
  isEmpty() {
    return this.length === 0
  }
  clear() {
    return (this.length = 0)
  }
}

module.exports = { Stack }
[解题]LeetCode-020-有效的括号.js
const { Stack } = require('./Stack')
/**
 * 20. 有效的括号
 * 给定一个只包括 '(',')','{','}','[',']' 的字符串 s ,判断字符串是否有效。
 * 有效字符串需满足:
 *   左括号必须用相同类型的右括号闭合。
 *   左括号必须以正确的顺序闭合。
 * @param {String} s
 */
const isValid = s => {
  if (s.length === 0) return true
  if (s.length % 2 === 1) return false
  const bracketsPair = {
    '(': ')',
    '[': ']',
    '{': '}'
  }
  const stack = new Stack()
  for (let index = 0; index < s.length; index++) {
    const char = s[index]
    if (bracketsPair.hasOwnProperty(char)) {
      stack.push(char)
    } else {
      if (bracketsPair[stack.peek()] === char) {
        stack.pop()
      } else {
        return false
      }
    }
  }
  return stack.length === 0
}

module.exports = { isValid }
[测试]LeetCode-020-有效的括号.test.js
const { isValid } = require('./LeetCode-020-有效的括号')

describe('isValid', () => {
  it('测试空字符串', () => {
    expect(isValid('')).toBe(true)
  })

  it('测试字符串长度为奇数', () => {
    expect(isValid('()(')).toBe(false)
  })

  it('测试 ()', () => {
    expect(isValid('()')).toBe(true)
  })

  it('测试 ()[]{}', () => {
    expect(isValid('()[]{}')).toBe(true)
  })

  it('测试 (]', () => {
    expect(isValid('(]')).toBe(false)
  })

  it('测试 ([)]', () => {
    expect(isValid('([)]')).toBe(false)
  })

  it('测试 {[]}', () => {
    expect(isValid('{[]}')).toBe(true)
  })
})