Java balanced expressions check {[()]}

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

    package Stack;
    
    import java.util.Stack;
    
    public class BalancingParenthesis {
    
     boolean isBalanced(String s) {
    
        Stack stack = new Stack();
    
        for (int i = 0; i < s.length(); i++) {
    
            if (s.charAt(i) == '(' || s.charAt(i) == '{' || s.charAt(i) == '[') {
    
                stack.push(s.charAt(i)); // push to the stack
    
            }
    
            if (s.charAt(i) == ')' || s.charAt(i) == '}' || s.charAt(i) == ']') {
    
                if (stack.isEmpty()) {
                    return false; // return false as there is nothing to match
                }
    
                Character top = stack.pop(); // to get the top element in the stack
    
                if (top == '(' && s.charAt(i) != ')' || top == '{' && s.charAt(i) != '}'
                        || top == '[' && s.charAt(i) != ']') {
    
                    return false;
                }
    
            }
    
        }
    
        if (stack.isEmpty()) {
            return true; // check if every symbol is matched
        }
    
        return false; // if some symbols were unmatched
    }
    
    public static void main(String[] args) {
    
        BalancingParenthesis obj = new BalancingParenthesis();
    
        System.out.println(obj.isBalanced("()[]{}[][]"));
    
    }
    
    }
    
    // Time Complexity : O(n)
    

提交回复
热议问题