js算法题-20230423

48 阅读1分钟

题目:判断字符产是否括号匹配

  • 一个字符串s可能包含{} () [] 三种括号
  • 判断s是否括号是匹配的
  • 如(a{b}c)匹配,而{a(b或{a(b)c}}就不匹配

相关知识补充

  • 先进后出
  • api:push pop length
  • 相关的:队列,堆(后面细讲)
const stack = []
stack.push(100) //入栈
stack.push(200)
stack.push(300)
const num = stack.pop() // 出栈
stack.length

逻辑结构 vs 物理结构

  • 栈 vs 数组
  • 栈,逻辑结构。理论模型,不论如何实现,不接受任何语言的限制
  • 数组,物理结构。真实的功能实现,受限于编程语言

解题思路

  • 遇到左括号{([就压栈
  • 遇到右括号})]就判断栈顶,匹配则出栈
  • 最后判断length是否为0

代码粘贴

// 判断左右括号是否匹配
function isMatch(left,right) {
 if(left === '{' && right === '}') return true
 if(left === '[' && right === ']') return true
 if(left === '(' && right === ')') return true
 return false
}

//判断是否括号匹配
function mathBracket(str) {
    const length = str.length
    if(length === 0) return true
    
    const stack = []
    
    const leftSymbols = '{[('
    const rightSymbols = '}])'
    
    for (leftSymbols.includes(s)) {
        //左括号压栈
        stack.push(s)
    } else if(rightSymbols.includes(s)) {
        //右括号 判断栈顶(是否出栈)
        const top = stack[stack.length - 1]
        if(isMatch(top,s)) {
            stack.pop()
        } else {
            return false
        }
    }
    return stack.length === 0
}

功能测试

const str = '{a(b[c]d)e}f'
console.info(123123,matchBracket(str))

单元测试

describe('判断字符产是否括号匹配', ()=>{
    it('正常情况', () => {
        const str = {a(b[c]d)e}f
        const res = matchBracket(str)
        expect(res).toBe(true)
    })
    it('不匹配', () => {
        const str = {a(b[(c]d)e}f
        const res = matchBracket(str)
        expect(res).toBe(false)
    })
    it('顺序不一致的', () => {
        const str = {a(b[c]d}e)f
        const res = matchBracket(str)
        expect(res).toBe(false)
    })
    it('空字符串', () => {
        const res = matchBracket('')
        expect(res).toBe(true)
    })
})

  

性能分析

  • 时间复杂度O(n)
  • 空间复杂度O(n)