web-dev-qa-db-fra.com

Java vérification des expressions équilibrées {[()]}

J'essaie de créer un programme qui prend une chaîne comme argument dans son constructeur. J'ai besoin d'une méthode qui vérifie si la chaîne est une expression entre parenthèses équilibrée. Il doit gérer ({[]}) chaque ouverture doit s'équilibrer avec son crochet de fermeture correspondant. Par exemple, un utilisateur pourrait entrer [({})] qui serait équilibré et} {serait déséquilibré. Cela n'a pas besoin de gérer des lettres ou des chiffres. J'ai besoin d'utiliser une pile pour ce faire.

On m'a donné ce pseudocode mais je ne sais pas comment l'implémenter en Java. Tout conseil serait génial. pseudocode

Mise à jour - désolé oublié de poster ce que j'avais jusqu'à présent. Son tout foiré parce qu'au début, j'essayais d'utiliser char, puis j'ai essayé un tableau .. je ne sais pas exactement où aller.

import Java.util.*;

public class Expression
{
  Scanner in = new Scanner(System.in);
  Stack<Integer> stack = new Stack<Integer>();



  public boolean check()
  {
    System.out.println("Please enter your expression.");
    String newExp = in.next();
    String[] exp = new String[newExp];
    for (int i = 0; i < size; i++)
    { 


      char ch = exp.charAt(i);
      if (ch == '(' || ch == '[' || ch == '{')
        stack.Push(i);
      else if (ch == ')'|| ch == ']' || ch == '}')
      {
        //nothing to match with
        if(stack.isEmpty())
        {  
          return false;
        }
        else if(stack.pop() != ch)
        { 
          return false;
        } 

      }            
    }
    if (stack.isEmpty())
    {
      return true;
    }
    else
    {
      return false;
    }
  }


}
16
Jess Anastasio

J'espère que ce code peut aider:

import Java.util.Stack;

public class BalancedParenthensies {

    public static void main(String args[]) {

        System.out.println(balancedParenthensies("{(a,b)}"));
        System.out.println(balancedParenthensies("{(a},b)"));
        System.out.println(balancedParenthensies("{)(a,b}"));
    }

    public static boolean balancedParenthensies(String s) {
        Stack<Character> stack  = new Stack<Character>();
        for(int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if(c == '[' || c == '(' || c == '{' ) {     
                stack.Push(c);
            } else if(c == ']') {
                if(stack.isEmpty() || stack.pop() != '[') {
                    return false;
                }
            } else if(c == ')') {
                if(stack.isEmpty() || stack.pop() != '(') {
                    return false;
                }           
            } else if(c == '}') {
                if(stack.isEmpty() || stack.pop() != '{') {
                    return false;
                }
            }

        }
        return stack.isEmpty();
    }
}
37
Smartoop
public static boolean isBalanced(String expression) {
  if ((expression.length() % 2) == 1) return false;
  else {
    Stack<Character> s = new Stack<>();
    for (char bracket : expression.toCharArray())
      switch (bracket) {
        case '{': s.Push('}'); break;
        case '(': s.Push(')'); break;
        case '[': s.Push(']'); break;
        default :
          if (s.isEmpty() || bracket != s.peek()) { return false;}
          s.pop();
      }
    return s.isEmpty();
  }
}

public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    String expression = in.nextLine();
    boolean answer = isBalanced(expression);
    if (answer) { System.out.println("YES");}
    else { System.out.println("NO");}

}
10
Madalina Raicu

L'équivalent de pseudo-code Java implémentation de l'algorithme est Java est le suivant).

import Java.util.HashMap;
import Java.util.Map;
import Java.util.Stack;

/**
 * @author Yogen Rai
 */
public class BalancedBracket {
    public static void main(String[] args) {
        String braces = "{{}(";
        if(isBalanced(braces)){
            System.out.println("YES");
        }else{
            System.out.println("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();
    }
}
8
Yogen Rai

Il est important d'utiliser une pile pour y pousser des symboles d'ouverture, puis lorsque vous rencontrez une accolade de fermeture, vous faites sortir l'élément du haut de la pile, puis vous le vérifiez pour voir s'il correspond au type d'accolade de fermeture. Voici une implémentation Java.

import Java.util.Stack;

public class Balanced {
    public static void main (String [] args)
    {
        String test_good = "()(){}{}{()}";
        String test_bad = "((({}{}))()";

        System.out.println(checkBalanced(test_good));
        System.out.println(checkBalanced(test_bad));
    }

    public static boolean checkBalanced(String check)
    {
        Stack<Character> S = new Stack<Character>();
        for(int a = 0; a < check.length(); a++)
        {
            char let = check.charAt(a);
            if(let == '[' || let == '{' || let == '(')
                S.Push(let);
            else if(let == ']' || let == '}' || let == ')')
            {
                if(S.empty())
                    return false;
                switch(let)
                {
                    // Opening square brace
                    case ']':
                        if (S.pop() != '[')
                            return false;
                        break;
                    // Opening curly brace
                    case '}':
                        if (S.pop() != '{')
                            return false;
                        break;
                    // Opening paren brace
                    case ')':
                        if (S.pop() != '(')
                            return false;
                        break;
                    default:
                        break;
                }
            }
        }
        if(S.empty())
            return true;
        return false;
    }
}
4
Neurax

Cela vous dérange si j'ajouterai ma solution de style bizarre basée sur JavaScript ?

C'est un truc ad hoc, pas pour la production, mais pour les interviews ou quelque chose comme ça. Ou juste pour le plaisir.

Le 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
}

Chèques:

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

Explication:

Il supprimera récursivement les paires fermées "()", "[]" et "{}":

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

Si à la fin, la longueur de la chaîne sera vide - c'est true, sinon - c'est false.

P.S. Peu de réponses

  • Pourquoi pas pour la production?

Parce que c'est lent, et ne vous souciez pas de la possibilité d'autres personnages entre les paires.

  • Pourquoi JS? Nous aimons Java

Parce que je suis développeur front-end mais que j'ai accompli la même tâche, cela peut donc être utile à quelqu'un. Et JS est aussi JVM lang =)

  • Mais pourquoi...

Parce que tous les développeurs JS sont fous, c'est pourquoi.

3
Sergei Panfilov

Vous poussez i - l'index - sur la pile et comparez avec ch. Vous devez pousser et faire éclater ch.

1
Maarten Bodewes

Une alternative à Hashmap et un moyen efficace serait d'utiliser un 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();
}
1
nisarg chitaliya

Utilisation de switch-case pour une meilleure lisibilité et gestion d'autres scénarios:

import Java.util.Scanner;
import Java.util.Stack;

public class JavaStack
{
    private static final Scanner scanner = new Scanner(System.in);

    public static void main(String[] args)
    {
        Scanner sc = new Scanner(System.in);
        while (sc.hasNext()) {
            String input = sc.next();
            System.out.println(isStringBalanced(input));
        }
        scanner.close();

    }

    private static boolean isStringBalanced(String testString)
    {
        Stack<Character> stack = new Stack<Character>();
        for (char c : testString.toCharArray()) {
            switch (c) {
                case '[':
                case '(':
                case '{':
                    stack.Push(c);
                    break;
                case ']':
                    if (stack.isEmpty() || stack.pop() != '[') {
                        return false;
                    }
                    break;
                case ')':
                    if (stack.isEmpty() || stack.pop() != '(') {
                        return false;
                    }
                    break;
                case '}':
                    if (stack.isEmpty() || stack.pop() != '{') {
                        return false;
                    }
                    break;
                default:
                    break;
            }
        }
        // stack has to be empty, if not, the balance was wrong
        return stack.empty();
    }
}
1
TechFree

Ce code fonctionne pour tous les cas, y compris les autres caractères non seulement entre parenthèses ex:
Veuillez saisir une entrée

{ibrahim[k]}
vrai

()[]{}[][]
vrai saddsd] faux

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;
    }
}
1
ibrahim karayel

Veuillez essayer ceci.

    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);
            }
        }

    }
1
Sami

Ceci est ma propre implémentation. J'ai essayé de le rendre le plus court et le plus clair possible:

public static boolean isBraceBalanced(String braces) {
    Stack<Character> stack = new Stack<Character>();

    for(char c : braces.toCharArray()) {
        if(c == '(' || c == '[' || c == '{') {
            stack.Push(c);
        } else if((c == ')' && (stack.isEmpty() || stack.pop() != '(')) ||
                  (c == ']' && (stack.isEmpty() || stack.pop() != '[')) ||
                  (c == '}' && (stack.isEmpty() || stack.pop() != '{'))) {
            return false;
        }
    }

    return stack.isEmpty();
}
1
FerDensetsu

Post tardif.

package com.prac.stack;

public class BalanceBrackets {

public static void main(String[] args) {
    String str = "{()}[]";
    char a[] = str.toCharArray();
    System.out.println(check(a));
}

static boolean check(char[] t) {
    Stackk st = new Stackk();
    for (int i = 0; i < t.length; i++) {
        if (t[i] == '{' || t[i] == '(' || t[i] == '[') {
            st.Push(t[i]);
        }
        if (t[i] == '}' || t[i] == ')' || t[i] == ']') {
            if (st.isEmpty()) {
                return false;
            } else if (!isMatching(st.pop(), t[i])) {
                return false;
            }
        }
    }

    if (st.isEmpty()) {
        return true;
    } else {
        return false;
    }
}

static boolean isMatching(char a, char b) {
    if (a == '(' && b == ')') {
        return true;
    } else if (a == '{' && b == '}') {
        return true;
    } else if (a == '[' && b == ']') {
        return true;
    } else {
        return false;
    }
}

}

1

Similaire à l'un des codes ci-dessus dans Java mais il a besoin d'une instruction else supplémentaire ajoutée afin d'éviter la comparaison de la pile avec des caractères autres que les accolades:

else if(bracketPair.containsValue(strExpression.charAt(i)))

public boolean isBalanced(String strExpression){
 Map<Character,Character> bracketPair = new HashMap<Character,Character>();
  bracketPair.put('(', ')');
  bracketPair.put('[', ']');
  bracketPair.put('{', '}');
  Stack<Character> stk = new Stack<Character>();
        for(int i =0;i<strExpression.length();i++){
            if(bracketPair.containsKey(strExpression.charAt(i)))
                stk.Push(strExpression.charAt(i));
            else if(bracketPair.containsValue(strExpression.charAt(i))) 
                if(stk.isEmpty()||bracketPair.get(stk.pop())!=strExpression.charAt(i))
                return false;
        }

        if(stk.isEmpty())
            return true;
            else
                return false;
        }
1
Ali Faisal
    import Java.io.IOException;
    import Java.util.ArrayList;
    import Java.util.List;
    import Java.util.Scanner;
    import Java.util.Stack;
    public class BalancedParenthesisWithStack {

    /*This is purely Java Stack based solutions without using additonal 
      data structure like array/Map */

    public static void main(String[] args) throws IOException {

        Scanner sc = new Scanner(System.in);

        /*Take list of String inputs (parenthesis expressions both valid and 
         invalid from console*/

        List<String> inputs=new ArrayList<>();
        while (sc.hasNext()) {

            String input=sc.next();
            inputs.add(input);

        }

        //For every input in above list display whether it is valid or 
         //invalid parenthesis expression

        for(String input:inputs){



        System.out.println("\nisBalancedParenthesis:"+isBalancedParenthesis
        (input));
        }
    }

    //This method identifies whether expression is valid parenthesis or not

    public static boolean isBalancedParenthesis(String expression){

        //sequence of opening parenthesis according to its precedence
         //i.e. '[' has higher precedence than '{' or '('
        String openingParenthesis="[{(";

        //sequence of closing parenthesis according to its precedence
        String closingParenthesis=")}]";

        //Stack will be pushed on opening parenthesis and popped on closing.
        Stack<Character> parenthesisStack=new Stack<>();


          /*For expression to be valid :
          CHECK :
          1. it must start with opening parenthesis [()...
          2. precedence of parenthesis  should be proper (eg. "{[" invalid  
                                                              "[{(" valid  ) 


          3. matching pair if(  '(' => ')')  i.e. [{()}(())] ->valid [{)]not 
          */
         if(closingParenthesis.contains
         (((Character)expression.charAt(0)).toString())){
            return false;
        }else{
        for(int i=0;i<expression.length();i++){

        char ch= (Character)expression.charAt(i);

        //if parenthesis is opening(ie any of '[','{','(') Push on stack
        if(openingParenthesis.contains(ch.toString())){
                parenthesisStack.Push(ch);
            }else if(closingParenthesis.contains(ch.toString())){
        //if parenthesis is closing (ie any of ']','}',')') pop stack
        //depending upon check-3 
                if(parenthesisStack.peek()=='(' && (ch==')') || 
                    parenthesisStack.peek()=='{' && (ch=='}') ||    
                    parenthesisStack.peek()=='[' && (ch==']')
                        ){
                parenthesisStack.pop();
                }
            }
        }

        return (parenthesisStack.isEmpty())? true : false;
        }
    }
1
Vinay Gade

Ceci est mon implémentation pour cette question. Ce programme autorise les nombres, les alphabets et les caractères spéciaux avec une chaîne d'entrée, mais les ignore simplement lors du traitement de la chaîne.

CODE:

import Java.util.Scanner;
import Java.util.Stack;

public class StringCheck {

    public static void main(String[] args) {
        boolean flag =false;
        Stack<Character> input = new Stack<Character>();
        System.out.println("Enter your String to check:");
        Scanner scanner = new Scanner(System.in);
        String sinput = scanner.nextLine();
        char[] c = new char[15];
        c = sinput.toCharArray();
        for (int i = 0; i < c.length; i++) {
            if (c[i] == '{' || c[i] == '(' || c[i] == '[')
                input.Push(c[i]);
            else if (c[i] == ']') {
                if (input.pop() == '[') {
                    flag = true;
                    continue;
                } else {
                    flag = false;
                    break;
                }
            } else if (c[i] == ')') {
                if (input.pop() == '(') {
                    flag = true;
                    continue;
                } else {
                    flag = false;
                    break;
                }
            } else if (c[i] == '}') {
                if (input.pop() == '{') {
                    flag = true;
                    continue;
                } else {
                    flag = false;
                    break;
                }
            }
        }
        if (flag == true)
            System.out.println("Valid String");
        else
            System.out.println("Invalid String");
        scanner.close();

    }

}
1
abubakkar

Voici le code. J'ai testé tous les cas de test possibles sur Hacker Rank.

static String isBalanced (String input) {

    Stack<Character> stack = new Stack<Character>();
    for (int i = 0; i < input.length(); i++) {
        Character ch = input.charAt(i);
        if (input.charAt(i) == '{' || input.charAt(i) == '['
                || input.charAt(i) == '(') {
            stack.Push(input.charAt(i));
        } else {
            if (stack.isEmpty() 
                    || (stack.peek() == '[' && ch != ']')
                    || (stack.peek() == '{' && ch != '}')
                    || (stack.peek() == '(' && ch != ')')) {
                return "NO";
            } else {
                stack.pop();
            }
        }
    }
    if (stack.empty())
        return "YES";
    return "NO";

}
0
Amit
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
Nik

En utilisant la référence de nœud, nous pouvons vérifier facilement

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
Birbal Singh

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
Pavan T

Cela peut être utilisé. Réussit tous les tests.

static String isBalanced(String s) {

    if(null == s){
        return "";
    }

    Stack<Character> bracketStack = new Stack<>();


    int length = s.length();

    if(length < 2 || length > 1000){
        return "NO";
    }


    for(int i = 0; i < length; i++){
        Character c= s.charAt(i);
        if(c == '(' || c == '{' || c == '[' ){
            bracketStack.Push(c);
        } else {
            if(!bracketStack.isEmpty()){
               char cPop = bracketStack.pop();

               if(c == ']' && cPop!= '['){
                  return "NO";
               }

               if(c == ')' && cPop!= '('){
                  return "NO";
               }

               if(c == '}' && cPop!= '{'){
                  return "NO";
               }
            } else{
                return "NO";
            }

        }
    }

    if(bracketStack.isEmpty()){
        return "YES";
    } else {
        return "NO";
    }

}
0
Pritam Banerjee
public static void main(String[] args) {
    System.out.println("is balanced : "+isBalanced("(){}[]<>"));
    System.out.println("is balanced : "+isBalanced("({})[]<>"));
    System.out.println("is balanced : "+isBalanced("({[]})<>"));
    System.out.println("is balanced : "+isBalanced("({[<>]})"));
    System.out.println("is balanced : "+isBalanced("({})[<>]"));


    System.out.println("is balanced : "+isBalanced("({[}])[<>]"));
    System.out.println("is balanced : "+isBalanced("([{})]"));
    System.out.println("is balanced : "+isBalanced("[({}])"));
    System.out.println("is balanced : "+isBalanced("[(<{>})]"));

    System.out.println("is balanced : "+isBalanced("["));
    System.out.println("is balanced : "+isBalanced("]"));

    System.out.println("is balanced : "+isBalanced("asdlsa"));
}

private static boolean isBalanced(String brackets){
    char[] bracketsArray = brackets.toCharArray();
    Stack<Character> stack = new Stack<Character>();
    Map<Character, Character> openingClosingMap = initOpeningClosingMap();

    for (char bracket : bracketsArray) {
        if(openingClosingMap.keySet().contains(bracket)){ 
            stack.Push(bracket);
        }else if(openingClosingMap.values().contains(bracket)){
            if(stack.isEmpty() || openingClosingMap.get(stack.pop())!=bracket){
                return false;
            }
        }else{
            System.out.println("Only  < > ( ) { } [ ] brackets  are allowed .");
            return false;
        }
    }
    return stack.isEmpty();
}

private static Map<Character, Character> initOpeningClosingMap() {
    Map<Character, Character> openingClosingMap = new HashMap<Character, Character>();
    openingClosingMap.put(Character.valueOf('('), Character.valueOf(')'));
    openingClosingMap.put(Character.valueOf('{'), Character.valueOf('}'));
    openingClosingMap.put(Character.valueOf('['), Character.valueOf(']'));
    openingClosingMap.put(Character.valueOf('<'), Character.valueOf('>'));
    return openingClosingMap;
}

Simplifier et rendre lisible. Utiliser une seule carte et les conditions minimales pour obtenir le résultat souhaité.

0
Himansu Meher
///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
Max.Futerman

Veuillez essayer ceci, je l'ai vérifié. Cela fonctionne correctement

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;
    }
}

Que diriez-vous de celui-ci, il utilise à la fois le concept de pile et les contrôles de compteur:

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
palslav

La méthode améliorée, de @Smartoop.

public boolean balancedParenthensies(String str) {
    List<Character> leftKeys = Arrays.asList('{', '(', '<', '[');
    List<Character> rightKeys = Arrays.asList('}', ')', '>', ']');

    Stack<Character> stack = new Stack<>();
    for (int i = 0; i < str.length(); i++) {
        char c = str.charAt(i);
        if (leftKeys.contains(c)) {
            stack.Push(c);
        } else if (rightKeys.contains(c)) {
            int index = rightKeys.indexOf(c);
            if (stack.isEmpty() || stack.pop() != leftKeys.get(index)) {
                return false;
            }
        }
    }
    return stack.isEmpty();
}
0
Zheng Xiaodong

Considérant que la chaîne se compose uniquement de '(' ')' '{' '}' '[' ']'. Voici une méthode de code qui retourne vrai ou faux selon que l'équation est équilibrée ou non.

private static boolean checkEquation(String input) {

    List<Character> charList = new ArrayList<Character>();

    for (int i = 0; i < input.length(); i++) {

        if (input.charAt(i) == '(' || input.charAt(i) == '{' || input.charAt(i) == '[') {
            charList.add(input.charAt(i));
        } else if ((input.charAt(i) == ')' && charList.get(charList.size() - 1) == '(')
                || (input.charAt(i) == '}' && charList.get(charList.size() - 1) == '{')
                || (input.charAt(i) == ']' && charList.get(charList.size() - 1) == '[')) {
            charList.remove(charList.size() - 1);
        } else
            return false;

    }

    if(charList.isEmpty())
        return true;
    else
        return false;
}
0
user8765332