JavaScript算法题:判断字符串是否括号匹配

946 阅读1分钟

Offer 驾到,掘友接招!我正在参与2022春招打卡活动,点击查看活动详情

一、题目描述:

判断字符串是否括号匹配

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

二、思路分析:

数据结构:栈

  • 先进后出
  • API:push pop length
  • 相关的:队列,堆

image.png

  • 栈 VS 数组
  • 栈,逻辑结构,是一个理论模型,不管如何实现,不受任何语言的限制
  • 数组,物理结构,真实的功能实现,受限于编程语言 栈和数组是两回事,数组可以实现栈,链表也可以实现栈

思路

  1. 遇到左括号{ ( [ 就压栈
  2. 遇到右括号} ) ]就判断栈顶,匹配则出栈
  3. 最后判断length是否为0
/**
 * @description 括号匹配
 * @author 有出路
 */

 /**
  * 判断是否括号匹配
  * @param str str
  */
 
 /**
  * 
  * @param left 左括号
  * @param right 右括号
  */
function isMatch(left:string,right:string):boolean{
    if(left === '{' && right === '}') return true
    if(left === '(' && right === ')') return true
    if(left === '[' && right === ']') return true

}




 function matchBracket(str:string):boolean{
     const length = str.length
     if(length===0) return true

     const stack = []

     const leftSymbols = '{(['
     const rightSymbols = '})]'


     for(let i=0;i < length;i++){
         const s = str[i]

         if(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 = 'abc{}(asdasd)'
 console.info(matchBracket(str))