Moment For Technology

Check whether the parentheses match the string

Posted on May 28, 2023, 12:09 a.m. by Kevin Arroyo
Category: The front end Tag: javascript algorithm

Offer to come, dig friends take it! I am participating in the 2022 Spring Recruit Punch card activity. Click here for details.

I. Title Description:

Determines whether the parentheses match the string

  • A string s may contain {} () [] parentheses
  • Check if s matches the parentheses
  • If (a{b}c) matches, {a(b or {a(b)c) does not match

Ii. Analysis of Ideas:

Data structure: stack

  • After the advanced
  • API: Push Pop Length
  • Related: queue, heap

  • Stack VS array
  • The stack, the logical structure, is a theoretical model, no matter how implemented, not constrained by any language. Right
  • Array, physical structure, real functionality implementation, limited by programming language

Stacks and arrays are two different things, arrays implement stacks, linked lists implement stacks

Train of thought

  1. Press the left parenthesis {([
  2. Close parenthesis})] is used to determine the top of the stack
  3. Finally, check whether length is 0
/ * * *@description Bracket matching *@author Have a way to * /

 /** * Checks whether the parentheses match *@param str str
 / * * * *@param Left Left parenthesis *@param Right close parenthesis */
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]

             // Open parenthesis, press the stack
         }else if(rightSymbols.includes(s)){
             // Close parentheses to determine the top of the stack
             const top = stack[stack.length-1]
                 return false}}}return stack.length === 0


 // Function test
 const str = 'abc{}(asdasd)'
Copy the code
About (Moment For Technology) is a global community with thousands techies from across the global hang out!Passionate technologists, be it gadget freaks, tech enthusiasts, coders, technopreneurs, or CIOs, you would find them all here.