How to write a function that recognises unbalanced brackets

前端 未结 2 1526
名媛妹妹
名媛妹妹 2021-01-17 05:46

I am trying to write a function that checks if a syntax is correct or not. If it is correct it returns \'ok\' else it returns the index of the error. So far my code works if

2条回答
  •  深忆病人
    2021-01-17 06:30

    An algorithm for doing this is, find an opening symbol, push it to a stack (or array, whatever). Find another opening symbol, push it to a stack. Find a closing symbol that matches the top of the stack, pop the opening symbol off the stack. Find a closing symbol that doesn't match the top of the stack, you found an error. Find a closing symbol and there's nothing on the stack, you found an error. Get to the end and still have symbols on the stack, you found an error.

提交回复
热议问题