Java balanced expressions check {[()]}

后端 未结 30 870
傲寒
傲寒 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<Character, Character> 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<Character> 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();
        }
    }
    
    0 讨论(0)
  • 2020-12-04 17:42

    Please try this I checked it. It works correctly

    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.util.HashMap;
    import java.util.Map;
    import java.util.Stack;
    public class CloseBrackets {
        private static Map<Character, Character> leftChar = new HashMap<>();
        private static Map<Character, Character> rightChar = new HashMap<>();
    
        static {
            leftChar.put('(', '(');
            rightChar.put(')', '(');
            leftChar.put('[', '[');
            rightChar.put(']', '[');
            leftChar.put('{', '{');
            rightChar.put('}', '{');
        }
    
        public static void main(String[] args) throws IOException {
            BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
            String st = bf.readLine();
            System.out.println(isBalanced(st));
        }
    
        public static boolean isBalanced(String str) {
    
            boolean result = false;
            if (str.length() < 2)
                return false;
            Stack<Character> stack = new Stack<>();
            /* For Example I gave input 
             * str = "{()[]}" 
             */
    
            for (int i = 0; i < str.length(); i++) {
    
                char ch = str.charAt(i);
                if (!rightChar.containsKey(ch) && !leftChar.containsKey(ch)) {
                    continue;
                }
                // Left bracket only add to stack. Other wise it will goes to else case 
                // For both above input how value added in stack 
                // "{(" after close bracket go to else case
                if (leftChar.containsKey(ch)) {
                    stack.push(ch);
                } else {
                    if (!stack.isEmpty()) {
                        // For both input how it performs
                        // 3rd character is close bracket so it will pop . pop value is "(" and map value for ")" key will "(" . So both are same . 
                        // it will return true. 
                        // now stack will contain only "{" , and travers to next up to end.
                        if (stack.pop() == rightChar.get(ch).charValue() || stack.isEmpty()) {
                            result = true;
                        } else {
                            return false;
                        }
                    } else {
                        return false;
                    }
                }
    
            }
            if (!stack.isEmpty())
                return result = false;
            return result;
        }
    }
    
    0 讨论(0)
  • 2020-12-04 17:42

    Using node reference we can check easily

    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.List;
    import java.util.Map;
    
    
    
    public class CloseBracketsBalance {
        private static final Map<String, String> closeBracket= new HashMap<>();
        private static final List<String> allBrac = new ArrayList<>();
    
        static {
            allBrac.add("[");
            allBrac.add("]");
            allBrac.add("{");
            allBrac.add("}");
            allBrac.add("(");
            allBrac.add(")");
            closeBracket.put("]", "[");
            closeBracket.put("}", "{");
            closeBracket.put(")", "(");
        }
    
        public static void main(String[] args) {
            System.out.println(checkSheetIsbalance("[{}({[]{}(dsfd)})]")); // return true
            System.out.println(checkSheetIsbalance("[{}({[]{}(dsfd}))]")); // return false
        }
    
        public static boolean checkSheetIsbalance(String c) {
            char[] charArr = c.toCharArray();
            Node node = null;
            for(int i=0,j=charArr.length;i<j;i++) {
                String ch = charArr[i]+"";
                if(!allBrac.contains(ch)) {
                    continue;
                }
    
                if(closeBracket.containsKey(ch)) {
                    // node close bracket               
                    if(node == null) {
                        return false;
                    }
                    if(!(node.nodeElement).equals(closeBracket.get(ch))) {
                        return false;
                    }
                    node = node.parent; 
                } else {
                    //make node for open bracket                
                     node = new Node(ch, node);
                }
            }       
    
            if(node != null) {
                return false;
            }
    
            return true;
        }
    }
    
    
    class Node {
        public String nodeElement;
        public Node parent;
        public Node(String el, Node p) {
            this.nodeElement = el;
            this.parent = p;
        }
    }
    
    0 讨论(0)
  • 2020-12-04 17:43

    How about this one, it uses both concept of stack plus counter checks:

    import java.util.*;
    class Solution{
    
    public static void main(String []argh)
    {
       Scanner sc = new Scanner(System.in);
       while (sc.hasNext()) {
          String input=sc.next();
          Stack<Character> stk = new Stack<Character>();
          char[] chr = input.toCharArray();
          int ctrl = 0, ctrr = 0;
          if(input.length()==0){
              System.out.println("true");
          }
          for(int i=0; i<input.length(); i++){
              if(chr[i]=='{'||chr[i]=='('||chr[i]=='['){
                  ctrl++;
                  stk.push(chr[i]);
                  //System.out.println(stk);
              }
          }
          for(int i=0; i<input.length(); i++){
              if(chr[i]=='}'||chr[i]==')'||chr[i]==']'){
                  ctrr++;
                  if(!stk.isEmpty())
                      stk.pop();
                  //System.out.println(stk);
              }
          }
          //System.out.println(stk);
          if(stk.isEmpty()&&ctrl==ctrr)
            System.out.println("true");
          else
            System.out.println("false");
          }
       }
    }
    
    0 讨论(0)
  • 2020-12-04 17:44

    This code works for all cases include other chars not only parentheses ex:
    Please enter input

    {ibrahim[k]}
    true

    ()[]{}[][]
    true saddsd] false

    public class Solution {
    
        private static Map<Character, Character> parenthesesMapLeft = new HashMap<>();
        private static Map<Character, Character> parenthesesMapRight = new HashMap<>();
    
        static {
            parenthesesMapLeft.put('(', '(');
            parenthesesMapRight.put(')', '(');
            parenthesesMapLeft.put('[', '[');
            parenthesesMapRight.put(']', '[');
            parenthesesMapLeft.put('{', '{');
            parenthesesMapRight.put('}', '{');
        }
    
        public static void main(String[] args) {
            System.out.println("Please enter input");
            Scanner scanner = new Scanner(System.in);
    
            String str = scanner.nextLine();
    
            System.out.println(isBalanced(str));
        }
    
        public static boolean isBalanced(String str) {
    
            boolean result = false;
            if (str.length() < 2)
                return false;
            Stack<Character> stack = new Stack<>();
            for (int i = 0; i < str.length(); i++) {
    
                char ch = str.charAt(i);
                if (!parenthesesMapRight.containsKey(ch) && !parenthesesMapLeft.containsKey(ch)) {
                    continue;
                }
                if (parenthesesMapLeft.containsKey(ch)) {
                    stack.push(ch);
                } else {
                    if (!stack.isEmpty() && stack.pop() == parenthesesMapRight.get(ch).charValue()) {
                        result = true;
                    } else {
                        return false;
                    }
                }
    
            }
            if (!stack.isEmpty())
                return result = false;
            return result;
        }
    }
    
    0 讨论(0)
  • 2020-12-04 17:45

    Do you mind, if I will add my freaky-style solution based on JavaScript?

    It's an ad-hoc stuff, not for production, but for the interviews or something like that. Or just for fun.

    The code:

    function reduceStr (str) {
      const newStr = str.replace('()', '').replace('{}', '').replace('[]', '')
      if (newStr !== str) return reduceStr(newStr)
      return newStr
    }
    
    function verifyNesting (str) {
      return reduceStr(str).length === 0
    }
    

    Checks:

    console.log(verifyNesting('[{{[(){}]}}[]{}{{(())}}]')) //correct
    console.log(verifyNesting('[{{[(){}]}}[]{}{({())}}]')) //incorrect
    

    Explanation:

    It will recursively remove closes pairs "()", "[]" and "{}":

    '[{{[(){}]}}[]{}{{(())}}]'
    '[{{}}[]{}{{(())}}]'
    '[{}{}{{()}}]'
    '[{}{{}}]'
    '[{{}}]'
    '[{}]'
    '' 
    

    If at the end string's length will be empty - it's true, if not - it's false.

    P.S. Few answers

    • Why not for production?

    Because it's slow, and don't care about the possibility of some other characters between pairs.

    • Why JS? We love Java

    Because I'm a frontend developer but met the same task, so perhaps it can be useful for somebody. And JS is also JVM lang =)

    • But why...

    Because all JS developers are crazy, that's why.

    0 讨论(0)
提交回复
热议问题