Skip to content

20. 有效的括号

20. 有效的括号

代码

javascript
// 20. 有效的括号:https://leetcode.cn/problems/valid-parentheses/description/
// 输入:s = "()"
// 输出:true

export function isValidParentheses (s) {
  const obj = {
    ')': '(',
    '}': '{',
    ']': '['
  }
  const list = []
  for (let i = 0; i < s.length; i++) {
    if (list.length && list[list.length - 1] === obj[s[i]]) {
      list.pop()
    } else {
      list.push(s[i])
    }
  }
  return list.length === 0
}
typescript
// 20. 有效的括号:https://leetcode.cn/problems/valid-parentheses/description/
// 输入:s = "()"
// 输出:true

export function isValidParentheses (s: string): boolean {
  const obj: { [key: string]: string } = {
    ')': '(',
    '}': '{',
    ']': '['
  }
  const list = []
  for (let i = 0; i < s.length; i++) {
    if (list.length && list[list.length - 1] === obj[s[i]]) {
      list.pop()
    } else {
      list.push(s[i])
    }
  }
  return list.length === 0
}

测试代码

ts
import { expect, test } from 'vitest'
import { isValidParentheses } from './typescript.ts'
import { isValidParentheses as isValidParenthesesJs } from './javascript.js'

test(`isValidParentheses('([])')`, () => {
  expect(isValidParentheses('([])')).toBe(true)
})

test(`isValidParenthesesJs('(}')`, () => {
  expect(isValidParenthesesJs('(}')).toBe(false)
})