How to check if a String is balanced?

前端 未结 8 1062
逝去的感伤
逝去的感伤 2020-12-06 11:57

I want to test if an input String is balanced. It would be balanced if there is a matching opening and closing parenthesis, bracket or brace.

example:
{} bal         


        
8条回答
  •  孤城傲影
    2020-12-06 12:52

    1) For every opening bracket: { [ ( push it to the stack.

    2) For every closing bracket: } ] ) pop from the stack and check whether the type of bracket matches. If not return false;

    i.e. current symbol in String is } and if poped from stack is anything else from { then return false immediately.

    3) If end of line and stack is not empty, return false, otherwise true.

提交回复
热议问题