Java balanced expressions check {[()]}

后端 未结 30 1081
傲寒
傲寒 2020-12-04 17:17

I am trying to create a program that takes a string as an argument into its constructor. I need a method that checks whether the string is a balanced parenthesized expressio

30条回答
  •  情歌与酒
    2020-12-04 17:39

    It's important to use a stack to push opening symbols onto it, then when you come across a closing brace you pop the element off the top of the stack and then you check it to see if it matches the type of closing brace. Here is a java implementation.

    import java.util.Stack;
    
    public class Balanced {
        public static void main (String [] args)
        {
            String test_good = "()(){}{}{()}";
            String test_bad = "((({}{}))()";
    
            System.out.println(checkBalanced(test_good));
            System.out.println(checkBalanced(test_bad));
        }
    
        public static boolean checkBalanced(String check)
        {
            Stack S = new Stack();
            for(int a = 0; a < check.length(); a++)
            {
                char let = check.charAt(a);
                if(let == '[' || let == '{' || let == '(')
                    S.push(let);
                else if(let == ']' || let == '}' || let == ')')
                {
                    if(S.empty())
                        return false;
                    switch(let)
                    {
                        // Opening square brace
                        case ']':
                            if (S.pop() != '[')
                                return false;
                            break;
                        // Opening curly brace
                        case '}':
                            if (S.pop() != '{')
                                return false;
                            break;
                        // Opening paren brace
                        case ')':
                            if (S.pop() != '(')
                                return false;
                            break;
                        default:
                            break;
                    }
                }
            }
            if(S.empty())
                return true;
            return false;
        }
    }
    

提交回复
热议问题