Java 平衡表达式检查 [()]

Posted

技术标签:

【中文标题】Java 平衡表达式检查 [()]【英文标题】:Java balanced expressions check [()]Java 平衡表达式检查 [()] 【发布时间】:2014-06-04 22:27:37 【问题描述】:

我正在尝试创建一个将字符串作为参数放入其构造函数的程序。我需要一种方法来检查字符串是否是平衡的括号表达式。它需要处理 ( [ ] ) 每个打开需要与其对应的右括号保持平衡。例如,用户可以输入平衡的 [()] 和不平衡的 。这不需要处理字母或数字。我需要使用堆栈来执行此操作。

我得到了这个伪代码,但不知道如何在 java 中实现它。任何建议都会很棒。

更新-抱歉忘记发布我到目前为止的内容。一切都搞砸了,因为起初我试图使用 char,然后我尝试了一个数组.. 我不确定该去哪里。

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;
    
  



【问题讨论】:

伪代码算法看起来很准确,为什么不发布到目前为止的实现。 void main(String[] args...) //code here ; 很抱歉,您甚至有伪代码,您必须将其翻译成Java。或者至少试一试,然后自己失败......也许,如果你的问题有任何努力的迹象 - 如FAQ中所述 - 将有助于获得一些帮助,而不是一些陈旧的冷嘲热讽。 .. 我发布了到目前为止我一直在做的工作,但我一开始忘记发布了,非常感谢 您首先将循环的索引压入堆栈,然后尝试弹出一个字符。您应该使用字符堆栈并将左大括号推到它上面。然后,当您找到右大括号时,将顶部元素弹出并查看它是否正确匹配左大括号。然后继续。如果最后有一个空堆栈,则字符串是平衡的。 codereview.stackexchange.com/questions/45916/… 看看你就会知道击球手的想法。 【参考方案1】:

平衡括号 在我的一次技术面试中得到了这个问题。应该通过仅使用数组来解决。 JAVA

public class Test1 
        public static void main(String[] args) 
            
            String arr = "()()()(((12())1()))()()()"; //true
            //String arr = "()()()(((12())1()))()()("; //false
            System.out.println(isValid(arr)); 
        
        
        static boolean isValid(String s)
            
            boolean valid;
            char[] array = s.toCharArray();
            char[] tempArray = new char[array.length];
            int parentesisCounter = 0;
            int tempCount = 0;
            
            for( int i = 0, m = 0; i < array.length; i++)
                if( array[i] == '(' || array[i] == ')' )
                    tempArray[m] = array[i];
                    m++;     
                
            
            
            for(int i = 0; i < tempArray.length; i++)
                if( tempArray[i] == '(' || tempArray[i] == ')')
                    tempCount++;
                
            
            
            char[] finalArray = new char[tempCount];
       
            System.arraycopy(tempArray, 0, finalArray, 0, tempCount);
            
            
            int countR = finalArray.length;
            int countL = 0;
            
            if((countR)%2 != 0)               
                return valid = false;
            else if(finalArray[0] == ')' || finalArray[countR-1] == '(' )
                return valid = false;
            
            
            for( int i = 0; i < finalArray.length; i++ )
                
                if( finalArray[countL] == '(' && finalArray[countL+1] == ')' )
                   countL+=2;
                   i++;
                   if(countL == countR)
                       return valid = true;
                   
                else if( finalArray[countR-1] == ')' && finalArray[countR-2] == '(' )
                   countR-=2;
                   if(countL == countR)
                       return valid = true;
                   
                else if( finalArray[countR-1] == ')' && finalArray[countR-2] == ')' )
                   countR--;
                   parentesisCounter--;
                   if(countL == countR)
                       return valid = true;
                    
                else if( finalArray[countL] == '(' && finalArray[countL+1] == '(' )
                   countL++;
                   parentesisCounter++;
                   if(countL == countR)
                       return valid = true;
                   
                else if( finalArray[countL] == ')' )
                   if(countL == countR+1)
                       return valid = true;
                   
                   parentesisCounter--;
                
             
            if(parentesisCounter == 0)
                valid = true;
            else valid = false;
            return valid;         
           
    

【讨论】:

这个问题很老了,今天会被认为是题外话。 Java 中已经有几个 解决方案来解决这个问题。你的有什么不同?请阅读How to Answer。 为什么这会被认为是题外话@Chris?很好编程相关 @Elikill58,它没有说明该代码有什么错误。一个主题问题将解释代码应该做什么,展示尝试,并清楚地解释代码的问题,以便答案可以纠正特定错误。这个问题没有这样做,因此吸引了一大堆没有价值的“这是我的解决方案”代码转储。 SO 并不是要炫耀您的代码或提供要盲目复制的代码。它是关于帮助用户学习的。 “与编程相关”不足以成为话题。详情请参阅help center。 @Chris 哦,是的,你的意思是它应该被关闭,因为需要更多的焦点/细节和清晰度。我通过你在谈论题外话,应该在 SE 网络的另一个站点上 大家好。感谢 cmets 和评论。虽然这个问题很老,但仍然与技术面试有关。我在 2021 年拿到了它,并感到有义务分享它。互联网上充斥着使用 Stack 的解决方案,但对不同数据结构的选择却很少。【参考方案2】:

此代码适用于所有情况,包括其他字符,不仅是括号 例如: 请输入输入法

ibrahim[k] 真的

()[][][] 真的

saddsd] 假的

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;
    

【讨论】:

【参考方案3】:
public static void main(String[] args) 
    
    String exp = "[()()]()";
    if(isBalanced(exp))
        System.out.println("Balanced");
    else
        System.out.println("Not Balanced");
    
    


public static boolean isBalanced(String exp)
    Stack<Character> stack = new Stack<Character>();
    
    for (int i = 0; i < exp.length(); i++) 
        char a = exp.charAt(i);
        char b =' ';
        if(!stack.isEmpty())
            b = stack.peek();
        
        if(a == '(' || a == '[' || a == '')
            stack.push(a);
            continue;
        
        else if((b == '(' && a == ')') || (b == '[' && a == ']') || (b == '' && a == ''))
            stack.pop();
            continue;
        
        else
            return false;
        
    
    return stack.isEmpty();

在这种情况下,堆栈始终是最可取的数据结构,您可以考虑时间和空间复杂度来尝试。

【讨论】:

【参考方案4】:

我们使用双端队列来轻松快速地找到平衡的字符串与否。在此我们正在检查字符串是否包含等于关闭和打开这些“()”、“”和“[]”的数量。在此,我们还检查了右括号应该在左括号之后。

import java.util.Deque;
import java.util.LinkedList;
public class TestPattern

    public static String pattern(String str)
        Deque<Character> deque = new LinkedList<>(); 
    for (char ch: str.toCharArray()) 
    if (ch == '' || ch == '[' || ch == '(') 
        deque.addFirst(ch);
     else 
        if (!deque.isEmpty() && ((deque.peekFirst() == '' && ch == '')
            || (deque.peekFirst() == '[' && ch == ']')
            || (deque.peekFirst() == '(' && ch == ')'))) 
            deque.removeFirst();
         else 
            return "Not Balanced";
        return "Balanced";

// the above method is retur balanced or not balanced string.


     public static void main(String []args)
       
        System.out.println(pattern("()"));
          System.out.println(pattern("()"));
     

【讨论】:

【参考方案5】:

我将这种暴力类型方法称为我们将字符串中的每个 () 或 或 [] 替换为“”,因此字符串的长度正在减少,如果字符串的长度没有改变,那么我只是在破坏否则循环,如果 String 的长度下降到 0,则意味着 String 中的所有内容都是平衡的,否则不是。

public class Question
public static void main(String[] args) 
    String target=" [ ( ) ] ",target2="( ) [ ]  ",target3="[ ( ) ] ( ( ) )",target4="(  [ )";
    target=target.replaceAll(" ","");
    target2=target2.replaceAll(" ", "");
    target3=target3.replaceAll(" ", "");
    target4=target4.replaceAll(" ", "");
    System.out.println(CheckExp(target));
    System.out.println(CheckExp(target2));
    System.out.println(CheckExp(target3));
    System.out.println(CheckExp(target4));

public static Boolean CheckExp(String target) 
    boolean flag = false;
    if (target.length() < 2 || target.length()%2!=0 ) 
        return flag;
    
    int first,last;
    while(true) 
        first=target.length();
            target = target.replace("()", "");
            target = target.replace("","");
            target = target.replace("[]","");
            last=target.length();
            if(first==last)
                break;
            flag= target.length() == 0;
    
    return flag;

【讨论】:

【参考方案6】:
static void checkBalanceParan(String s)
Stack<Character>stk=new Stack<>();

int i=0;
int size=s.length();
while(i<size)
    if(s.charAt(i)==''||s.charAt(i)=='('||s.charAt(i)=='[')
        stk.push(s.charAt(i));
        i++;
    
    else if(s.charAt(i)==''&&!stk.empty()&&stk.peek()=='')
            int x=stk.pop();
            i++;
    else if(s.charAt(i)==')'&&!stk.empty()&&stk.peek()=='(')
        
        int x=stk.pop();
        i++;
        
    else if(s.charAt(i)==']'&&!stk.empty()&&stk.peek()=='[')
        int x=stk.pop();
        i++;

    else
    System.out.println("not Balanced");
        return;
        
    
System.out.println("Balanced");

【讨论】:

【参考方案7】:

我解决这个问题的方法略有不同,我观察到了这个问题的两个关键点。

    开括号应始终伴随着相应的闭括号。 不同的开括号可以放在一起,但不同的闭括号不能放在一起。

所以我将这些要点转换为易于实现和易于理解的格式。

    我用不同的数字表示不同的大括号 开括号用正号,闭括号用负号。

例如:" ( ) [ ]" 将是 "1 -1 2 -2 3 -3" 是有效的括号。 对于平衡括号,正数可以相邻,因为负数应该是堆栈顶部的正数。

下面是代码:

import java.util.Stack;

public class Main 
    public static void main (String [] args)
    
        String value = "()()()";
        System.out.println(Main.balancedParanthesis(value));
       
    

public static boolean balancedParanthesis(String s) 
        
        
        
        char[] charArray=s.toCharArray();
        
        int[] integerArray=new int[charArray.length];
        
        
        // creating braces with equivalent numeric values
        for(int i=0;i<charArray.length;i++) 
            
            if(charArray[i]=='') 
                integerArray[i]=1;
            
            else if(charArray[i]=='') 
                integerArray[i]=-1;
            
            else if(charArray[i]=='[') 
                integerArray[i]=2;
            
            else if(charArray[i]==']') 
                integerArray[i]=-2;
            
            else if(charArray[i]=='(') 
                integerArray[i]=3;
            
            else  
                integerArray[i]=-3;
            
        
        
        Stack<Integer> stack=new Stack<Integer>();
        
        for(int i=0;i<charArray.length;i++) 
            
            if(stack.isEmpty()) 
                if(integerArray[i]<0) 
                    stack.push(integerArray[i]);
                    break;
            
                    stack.push(integerArray[i]);
            
            else
                if(integerArray[i]>0) 
                    stack.push(integerArray[i]);
                
                else 
                    if(stack.peek()==-(integerArray[i])) 
                        stack.pop();
                    
                    else 
                        break;
                    
                
            
        
        return stack.isEmpty();
    

【讨论】:

您好 Nava Chaitanya,欢迎来到 ***。如果您在代码中发布一些解释,人们将不胜感激。【参考方案8】:

算法的等效java实现的伪代码是java如下。

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

【讨论】:

不错!这比其他答案更具数据驱动力 - 因此您可以轻松地将其扩展为包含 100 种不同类型的大括号,而无需更改代码(当然,如果您传递了 braces 数据!)【参考方案9】:
public class StackProb 

public static void main(String[] args) 

    Scanner sc = new Scanner(System.in);
    List<Boolean> list = new ArrayList<>();

    while (sc.hasNextLine()) 
        String s=sc.nextLine();
        if(!s.isEmpty()) 
            list.add(isBalanced(s));
            //System.out.println(isBalanced(s));
        else 
            sc.close();
            break;
        
    

    for (int i = 0; i < list.size(); i++) 
        System.out.println(list.get(i) + " ");
    



private static boolean isBalanced(String s) 
    boolean res = false;
    Stack<Character> stack = new Stack();
    int countA = 0;
    int countB = 0;
    for (int i = 0; i < s.length(); i++) 

        if(s.charAt(i)=='' || s.charAt(i)=='(' || s.charAt(i)=='[') 

            stack.push(s.charAt(i));
            countA++;
        


        if(s.charAt(i)=='' || s.charAt(i)==')' || s.charAt(i)==']') 

            stack.push(s.charAt(i));
            countB++;
        

        if(stack.firstElement()=='' || stack.firstElement()==')' || stack.firstElement()==']') 
            countB++;
        


    
    if(countA==countB) 
        return true;
    
    return false;


【讨论】:

这是解决堆栈平衡问题的简单方法。解决了 HackerRank hackerrank.com/challenges/java-stack/… 问题,所有测试用例都通过了【参考方案10】:

使用java.util.Stack数据结构实现匹配括号的代码sn-p-

    //map for storing matching parenthesis pairs
    private static final Map<Character, Character> matchingParenMap = new HashMap<>();

    //set for storing opening parenthesis
    private static final Set<Character> 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<Character> 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(***Exception s) 
         catch(StackUnderflowException s1) 
         return false;
    

我已经在博客http://hetalrachh.home.blog/2019/12/25/stack-data-structure/上解释了代码sn-p和使用的算法

【讨论】:

【参考方案11】:
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)

【讨论】:

【参考方案12】:
import java.util.Objects;
import java.util.Stack;

public class BalanceBrackets 

    public static void main(String[] args) 
        String input="(a[d]b)";
        System.out.println(isBalance(input));  ;
    

    private static boolean isBalance(String input) 
        Stack <Character> stackFixLength = new Stack();

        if(input == null || input.length() < 2) 
            throw  new IllegalArgumentException("in-valid arguments");
        

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

            if (input.charAt(i) == '(' || input.charAt(i) == '' || input.charAt(i) == '[') 
                stackFixLength.push(input.charAt(i));
            

            if (input.charAt(i) == ')' || input.charAt(i) == '' || input.charAt(i) == ']') 

                if(stackFixLength.empty()) return false;

                char b = stackFixLength.pop();

                if (input.charAt(i) == ')' && b == '(' || input.charAt(i) == '' && b == '' || input.charAt(i) == ']' && b == '[') 
                    continue;
                 else 
                    return false;
                
            
        

        return stackFixLength.isEmpty();
    

【讨论】:

【参考方案13】:

这是代码。我已经在 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";


【讨论】:

【参考方案14】:

后期发布。

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;
    



【讨论】:

【参考方案15】:
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 ****");
           

【讨论】:

【参考方案16】:
///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();

【讨论】:

【参考方案17】:

使用 switch-case 来提高可读性和处理其他场景:

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

【讨论】:

【参考方案18】:

Hashmap 的一种替代方法和一种有效的方法是使用 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();

【讨论】:

我认为检查s == null 没有用,因为在这种情况下s.length() 会抛出异常。 s == null的条件下,不会达到检查s.length()的条件。这在 java 中称为短路评估,如果操作数是 || 并且第一个条件本身为真,它将返回真而不检查其他条件。这就是为什么我们首先检查空条件【参考方案19】:

考虑到字符串仅包含 '(' ')' '' '' '[' ']'。这是一个代码方法,根据方程是否平衡返回真或假。

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;

【讨论】:

【参考方案20】:

改进的方法,来自@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();

【讨论】:

【参考方案21】:

使用节点引用我们可以轻松检查

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;
    

【讨论】:

【参考方案22】:
    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;
        
    

【讨论】:

您好,欢迎来到 SO。一般来说,添加某种评论或解释而不是仅仅给出代码会更好。所以请edit您的回答并尝试描述它的作用和方式。谢谢! 请看代码的详细描述,代码插入为cmets。希望对您有所帮助【参考方案23】:

请试试这个我检查过。它工作正常

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;
    

【讨论】:

【参考方案24】:

类似于 JAVA 中的上述代码之一,但它需要再添加一条 else 语句以避免与大括号以外的字符进行堆栈比较:

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;
        

【讨论】:

【参考方案25】:

您介意我添加基于 javascript 的怪异风格的解决方案吗?

这是一个临时的东西,不是为了制作,而是为了采访或类似的东西。或者只是为了好玩。

代码

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

检查

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

说明

它将递归地删除关闭对“()”、“[]”和“”:

'[[()][](())]'
'[[](())]'
'[()]'
'[]'
'[]'
'[]'
'' 

如果最后字符串的长度为空 - 它是 true,如果不是 - 它是 false

P.S.答案很少

为什么不用于生产?

因为它很慢,而且不关心对之间可能存在一些其他字符。

为什么选择 JS?我们喜欢 Java

因为我是一名前端开发人员,但遇到了同样的任务,所以也许它对某人有用。而且JS也是JVM lang =)

但是为什么...

因为所有的 JS 开发者都很疯狂,这就是原因。

【讨论】:

【参考方案26】:

这个可以用。通过所有测试。

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


【讨论】:

【参考方案27】:

希望这段代码能帮到你:

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

【讨论】:

我看到你可以合并嵌套的 IF。【参考方案28】:

这是我自己的实现。我试图让它尽可能最短和最清晰:

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

【讨论】:

【参考方案29】:

这个怎么样,它同时使用堆栈和计数器检查的概念:

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

【讨论】:

【参考方案30】:
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;

简化并提高可读性。 仅使用一张地图和最低条件即可获得所需的结果。

【讨论】:

以上是关于Java 平衡表达式检查 [()]的主要内容,如果未能解决你的问题,请参考以下文章

检查正则表达式是不是通过正则表达式有效

正则表达式平衡括号

java中检查姓名的正则表达式

如何确定表达式是不是在堆栈中具有平衡括号? [复制]

如何纠正正则表达式中的不平衡括号错误?

正则表达式:匹配多个平衡组