Java balanced expressions check {[()]}

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

    Please try this.

        import java.util.Stack;
    
        public class PatternMatcher {
            static String[] patterns = { "{([])}", "{}[]()", "(}{}]]", "{()", "{}" };
            static String openItems = "{([";
    
            boolean isOpen(String sy) {
                return openItems.contains(sy);
            }
    
            String getOpenSymbol(String byCloseSymbol) {
                switch (byCloseSymbol) {
                case "}":
                    return "{";
                case "]":
                    return "[";
                case ")":
                    return "(";
    
                default:
                    return null;
                }
            }
    
            boolean isValid(String pattern) {
    
                if(pattern == null) {
                    return false;
                }
    
                Stack stack = new Stack();
                char[] symbols = pattern.toCharArray();
    
                if (symbols.length == 0 || symbols.length % 2 != 0) {
                    return false;
                }
    
                for (char c : symbols) {
                    String symbol = Character.toString(c);
                    if (isOpen(symbol)) {
                        stack.push(symbol);
                    } else {
                        String openSymbol = getOpenSymbol(symbol);
                        if (stack.isEmpty() 
                                || openSymbol == null 
                                || !openSymbol.equals(stack.pop())) {
                            return false;
                        }
                    }
                }
                return stack.isEmpty();
            }
    
            public static void main(String[] args) {
                PatternMatcher patternMatcher = new PatternMatcher();
    
                for (String pattern : patterns) {
                    boolean valid = patternMatcher.isValid(pattern);
                    System.out.println(pattern + "\t" + valid);
                }
            }
    
        }
    

提交回复
热议问题