Java balanced expressions check {[()]}

后端 未结 30 871
傲寒
傲寒 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:45
    import java.util.Stack;
    
            public class StackParenthesisImplementation {
                public static void main(String[] args) {
                    String Parenthesis = "[({})]";
                    char[] charParenthesis  = Parenthesis.toCharArray();
                    boolean evalParanthesisValue = evalParanthesis(charParenthesis);
                    if(evalParanthesisValue == true)
                        System.out.println("Brackets are good");
                    else
                        System.out.println("Brackets are not good");
                }
                static boolean evalParanthesis(char[] brackets)
                {       
                    boolean IsBracesOk = false;
                    boolean PairCount = false;
                    Stack<Character> stack = new Stack<Character>();
                    for(char brace : brackets)
                    {                       
                        if(brace == '(' || brace == '{' || brace == '['){
                            stack.push(brace);  
                            PairCount = false;
                        }
                        else if(!stack.isEmpty())
                        {
                            if(brace == ')' || brace == '}' || brace == ']')
                            {
                                char CharPop = stack.pop();
                                if((brace == ')' && CharPop == '('))
                                {
                                    IsBracesOk = true; PairCount = true;
                                }
                                else if((brace == '}') && (CharPop == '{'))
                                {
                                    IsBracesOk = true; PairCount = true;
                                }
                                else if((brace == ']') && (CharPop == '['))
                                {
                                    IsBracesOk = true; PairCount = true;
                                }
                                else 
                                {
                                    IsBracesOk = false;
                                    PairCount = false;
                                    break;
                                }
                            }   
                        }
                    }   
                    if(PairCount == false)
                    return IsBracesOk = false;
                    else
                        return IsBracesOk = true;
                }
            }
    
    0 讨论(0)
  • 2020-12-04 17:46
    ///check Parenthesis
    public boolean isValid(String s) {
        Map<Character, Character> map = new HashMap<>();
        map.put('(', ')');
        map.put('[', ']');
        map.put('{', '}');
        Stack<Character> stack = new Stack<>();
        for(char c : s.toCharArray()){
            if(map.containsKey(c)){
                stack.push(c);
            } else if(!stack.empty() && map.get(stack.peek())==c){
                stack.pop();
            } else {
                return false;
            }
        }
        return stack.empty();
    }
    
    0 讨论(0)
  • 2020-12-04 17:46
    package Stack;
    
    import java.util.Stack;
    
    public class BalancingParenthesis {
    
     boolean isBalanced(String s) {
    
        Stack<Character> stack = new Stack<Character>();
    
        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)
    
    0 讨论(0)
  • 2020-12-04 17:47

    An alternative to Hashmap and an efficient way would be to use a Deque:

    public boolean isValid(String s) 
    {
        if(s == null || s.length() == 0)
            return true;
    
         Deque<Character> stack = new ArrayDeque<Character>();
         for(char c : s.toCharArray()) 
         {
             if(c == '{')
                stack.addFirst('}');
    
              else if(c == '(')
                stack.addFirst(')');
    
               else if(c == '[')
                  stack .addFirst(']');
    
                else if(stack.isEmpty() || c != stack.removeFirst())
                   return false;
         }
                 return stack.isEmpty();
    }
    
    0 讨论(0)
  • 2020-12-04 17:48
    public void validateExpression(){
    
        if(!str.isEmpty() && str != null){
            if( !str.trim().equals("(") && !str.trim().equals(")")){
    
                char[] chars = str.toCharArray();
    
                for(char c: chars){
                    if(!Character.isLetterOrDigit(c) && c == '('  || c == ')') {
                        charList.add(c);
                    }
                }
    
                for(Character ele: charList){                   
                    if(operatorMap.get(ele) != null && operatorMap.get(ele) != 0){                      
                        operatorMap.put(ele,operatorMap.get(ele)+1);
                    }else{
                        operatorMap.put(ele,1);
                    }
                }
    
                for(Map.Entry<Character, Integer> ele: operatorMap.entrySet()){
                    System.out.println(String.format("Brace Type \"%s\" and count is \"%d\" ", ele.getKey(),ele.getValue()));                   
                }
    
                if(operatorMap.get('(') == operatorMap.get(')')){
                    System.out.println("**** Valid Expression ****");
                }else{
                    System.out.println("**** Invalid Expression ****");
                }
    
            }else{
                System.out.println("**** Incomplete expression to validate ****");
            }
    
        }else{
            System.out.println("**** Expression is  empty or null ****");
        }       
    }
    
    0 讨论(0)
  • 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<String> stack = new Stack<String>();
                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);
                }
            }
    
        }
    
    0 讨论(0)
提交回复
热议问题