Java balanced expressions check {[()]}

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

    Late Post.

    package com.prac.stack;
    
    public class BalanceBrackets {
    
    public static void main(String[] args) {
        String str = "{()}[]";
        char a[] = str.toCharArray();
        System.out.println(check(a));
    }
    
    static boolean check(char[] t) {
        Stackk st = new Stackk();
        for (int i = 0; i < t.length; i++) {
            if (t[i] == '{' || t[i] == '(' || t[i] == '[') {
                st.push(t[i]);
            }
            if (t[i] == '}' || t[i] == ')' || t[i] == ']') {
                if (st.isEmpty()) {
                    return false;
                } else if (!isMatching(st.pop(), t[i])) {
                    return false;
                }
            }
        }
    
        if (st.isEmpty()) {
            return true;
        } else {
            return false;
        }
    }
    
    static boolean isMatching(char a, char b) {
        if (a == '(' && b == ')') {
            return true;
        } else if (a == '{' && b == '}') {
            return true;
        } else if (a == '[' && b == ']') {
            return true;
        } else {
            return false;
        }
    }
    
    }
    

提交回复
热议问题