Java balanced expressions check {[()]}

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

    The pseudo code equivalent java implementation of the algorithm is java is as follows.

    import java.util.HashMap;
    import java.util.Map;
    import java.util.Stack;
    
    /**
     * @author Yogen Rai
     */
    
    public class BalancedBraces
    {
        public static void main(String[] args) {
            System.out.println(isBalanced("{{}}") ? "YES" : "NO"); // YES
            System.out.println(isBalanced("{{}(") ? "YES" : "NO"); // NO 
            System.out.println(isBalanced("{()}") ? "YES" : "NO"); // YES 
            System.out.println(isBalanced("}{{}}") ? "YES" : "NO"); // NO
        }
    
        public static boolean isBalanced(String brackets) {
            // set matching pairs
            Map braces = new HashMap<>();
            braces.put('(', ')');
            braces.put('[',']');
            braces.put('{','}');
    
            // if length of string is odd, then it is not balanced
            if (brackets.length() % 2 != 0) {
                return false;
            }
    
            // travel half until openings are found and compare with
            // remaining if the closings matches
            Stack halfBraces = new Stack();
            for(char ch: brackets.toCharArray()) {
                if (braces.containsKey(ch)) {
                    halfBraces.push(braces.get(ch));
                }
                // if stack is empty or if closing bracket is not equal to top of stack,
                // then braces are not balanced
                else if(halfBraces.isEmpty() || ch != halfBraces.pop()) {
                    return false;
                }
            }
            return halfBraces.isEmpty();
        }
    }
    

提交回复
热议问题