Java balanced expressions check {[()]}

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

    public void validateExpression(){
    
        if(!str.isEmpty() && str != null){
            if( !str.trim().equals("(") && !str.trim().equals(")")){
    
                char[] chars = str.toCharArray();
    
                for(char c: chars){
                    if(!Character.isLetterOrDigit(c) && c == '('  || c == ')') {
                        charList.add(c);
                    }
                }
    
                for(Character ele: charList){                   
                    if(operatorMap.get(ele) != null && operatorMap.get(ele) != 0){                      
                        operatorMap.put(ele,operatorMap.get(ele)+1);
                    }else{
                        operatorMap.put(ele,1);
                    }
                }
    
                for(Map.Entry ele: operatorMap.entrySet()){
                    System.out.println(String.format("Brace Type \"%s\" and count is \"%d\" ", ele.getKey(),ele.getValue()));                   
                }
    
                if(operatorMap.get('(') == operatorMap.get(')')){
                    System.out.println("**** Valid Expression ****");
                }else{
                    System.out.println("**** Invalid Expression ****");
                }
    
            }else{
                System.out.println("**** Incomplete expression to validate ****");
            }
    
        }else{
            System.out.println("**** Expression is  empty or null ****");
        }       
    }
    

提交回复
热议问题