Java balanced expressions check {[()]}

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

    I hope this code can help:

    import java.util.Stack;
    
    public class BalancedParenthensies {
    
        public static void main(String args[]) {
    
            System.out.println(balancedParenthensies("{(a,b)}"));
            System.out.println(balancedParenthensies("{(a},b)"));
            System.out.println(balancedParenthensies("{)(a,b}"));
        }
    
        public static boolean balancedParenthensies(String s) {
            Stack stack  = new Stack();
            for(int i = 0; i < s.length(); i++) {
                char c = s.charAt(i);
                if(c == '[' || c == '(' || c == '{' ) {     
                    stack.push(c);
                } else if(c == ']') {
                    if(stack.isEmpty() || stack.pop() != '[') {
                        return false;
                    }
                } else if(c == ')') {
                    if(stack.isEmpty() || stack.pop() != '(') {
                        return false;
                    }           
                } else if(c == '}') {
                    if(stack.isEmpty() || stack.pop() != '{') {
                        return false;
                    }
                }
    
            }
            return stack.isEmpty();
        }
    }
    

提交回复
热议问题