Java balanced expressions check {[()]}

后端 未结 30 1155
傲寒
傲寒 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

    Code snippet for implementing matching parenthesis using java.util.Stack data structure -

        //map for storing matching parenthesis pairs
        private static final Map matchingParenMap = new HashMap<>();
    
        //set for storing opening parenthesis
        private static final Set openingParenSet = new HashSet<>();
    
        static {
             matchingParenMap.put(')','(');
             matchingParenMap.put(']','['); 
             matchingParenMap.put('}','{'); 
             openingParenSet.addAll(matchingParenMap.values());  
        }
    
        //check if parenthesis match
        public static boolean hasMatchingParen(String input) {
          try {
             //stack to store opening parenthesis
             Stack parenStack = new Stack<>();
    
             for(int i=0; i< input.length(); i++) {
                char ch = input.charAt(i);
    
                //if an opening parenthesis then push to the stack
                if(openingParenSet.contains(ch)) {
                     parenStack.push(ch);
                } 
    
                //for closing parenthesis
                if(matchingParenMap.containsKey(ch)) {
                     Character lastParen = parenStack.pop();
                     if(lastParen != matchingParenMap.get(ch)) {
                        return false;
                     } 
                }
             }
    
             //returns true if the stack is empty else false
             return parenStack.isEmpty();
           }
             catch(StackOverflowException s) {}
             catch(StackUnderflowException s1) {}
             return false;
        }
    

    I have explained the code snippet and the algorithm used on blog http://hetalrachh.home.blog/2019/12/25/stack-data-structure/

提交回复
热议问题