Java balanced expressions check {[()]}

后端 未结 30 1141
傲寒
傲寒 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:45

    import java.util.Stack;
    
            public class StackParenthesisImplementation {
                public static void main(String[] args) {
                    String Parenthesis = "[({})]";
                    char[] charParenthesis  = Parenthesis.toCharArray();
                    boolean evalParanthesisValue = evalParanthesis(charParenthesis);
                    if(evalParanthesisValue == true)
                        System.out.println("Brackets are good");
                    else
                        System.out.println("Brackets are not good");
                }
                static boolean evalParanthesis(char[] brackets)
                {       
                    boolean IsBracesOk = false;
                    boolean PairCount = false;
                    Stack stack = new Stack();
                    for(char brace : brackets)
                    {                       
                        if(brace == '(' || brace == '{' || brace == '['){
                            stack.push(brace);  
                            PairCount = false;
                        }
                        else if(!stack.isEmpty())
                        {
                            if(brace == ')' || brace == '}' || brace == ']')
                            {
                                char CharPop = stack.pop();
                                if((brace == ')' && CharPop == '('))
                                {
                                    IsBracesOk = true; PairCount = true;
                                }
                                else if((brace == '}') && (CharPop == '{'))
                                {
                                    IsBracesOk = true; PairCount = true;
                                }
                                else if((brace == ']') && (CharPop == '['))
                                {
                                    IsBracesOk = true; PairCount = true;
                                }
                                else 
                                {
                                    IsBracesOk = false;
                                    PairCount = false;
                                    break;
                                }
                            }   
                        }
                    }   
                    if(PairCount == false)
                    return IsBracesOk = false;
                    else
                        return IsBracesOk = true;
                }
            }
    

提交回复
热议问题