How to check if a String is balanced?

前端 未结 8 1055
逝去的感伤
逝去的感伤 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:42

    Yes, a stack is a suitable choice for the task, or you could use a recursive function. If you use a stack, then the idea is you push each opening bracket on the stack, when you encounter a closing bracket you check that the top of the stack matches it. If it matches, pop it off, if not that is an error. When complete, the stack should be empty.

    import java.util.Stack;
    public class Balanced {
        public static boolean isBalanced(String in)
        {
            Stack st = new Stack();
    
            for(char chr : in.toCharArray())
            {
                switch(chr) {
    
                    case '{':
                    case '(':
                    case '[':
                        st.push(chr);
                        break;
    
                    case ']':
                        if(st.isEmpty() || st.pop() != '[') 
                            return false;
                        break;
                    case ')':
                        if(st.isEmpty() || st.pop() != '(')
                            return false;
                        break;
                    case '}':
                        if(st.isEmpty() || st.pop() != '{')
                            return false;
                        break;
                }
            }
            return st.isEmpty();
        }
        public static void main(String args[]) {
            if(args.length != 0) {
                if(isBalanced(args[0]))
                    System.out.println(args[0] + " is balanced");
                else
                    System.out.println(args[0] + " is not balanced");
            }
        }
    }
    

提交回复
热议问题