【问题标题】:Java: Checking the correctness of brackets using stacksJava:使用堆栈检查括号的正确性
【发布时间】:2018-01-21 19:20:05
【问题描述】:

在这个程序中,我试图检查输入字符串中的括号是否平衡。例如,(9*[3+4]) 是正确的,{10/[4+9) 不是。但是,每当我尝试运行我的程序并输入输入时。

出现了很多问题。当我输入字符串([{}]) 时,它说括号不平衡,当我输入([]) 时,它给了我一个空堆栈异常。我对堆栈的想法还很陌生,所以我遇到了很多麻烦。

import java.io.*;
import java.util.*;
import java.util.Stack;

public class BracketCheck {
    public static void main(String args[]) {
        Stack stk = new Stack();
        Scanner s = new Scanner(System.in);
        boolean balance = true;

        System.out.println("Enter a string");
        String str = s.nextLine();

        for(int i = 0; i < str.length(); i++) {
            if(str.charAt(i) == '(' || str.charAt(i) == '[' 
            || str.charAt(i) == '{') { //if the char is an opening bracket then add to stack
                stk.push(str.charAt(i));
            }
            else if(str.charAt(i) == ')' || str.charAt(i) == ']' ||
            str.charAt(i) == '}') { //if char is a closing bracket
                if(!stk.isEmpty()) {
                    System.out.println(stk.peek()); // to check if the bracket was added
                    if((stk.pop().equals('(') && str.charAt(i) != ')') ||
                    (stk.pop().equals('[') && str.charAt(i) != ']') ||
                    (stk.pop().equals('{') && str.charAt(i) != '}')) {
                        // this is where i believe the empty stack exception occurs
                        balance = false;
                        System.out.println("Brackets don't match");
                        break;
                    }
                }
                else { // flase because there is no opeing bracket to match with the closing bracket
                    balance = false;
                    System.out.println("There is no opening bracket");
                    break;
                }
            }
        }
        if (balance == true) {
            System.out.println("The equation is balanced");
        }
        else {
            System.out.println("The equation is not balanced");
        }
    }
}

【问题讨论】:

  • 旁白:if ("([{".indexOf(str.charAt(i)) &gt;= 0) 是一种更简单的方法来检查您是否在左括号中。

标签: java string char stack


【解决方案1】:

问题是当您检查括号是否匹配时,您一直在调用stk.pop()

if((stk.pop().equals('(') && str.charAt(i) != ')') ||
    (stk.pop().equals('[') && str.charAt(i) != ']') ||
    (stk.pop().equals('{') && str.charAt(i) != '}')) {

弹出一次,存储在一个变量中,在条件中使用该变量而不是stk.pop()

Character pop = stk.pop();
if((pop.equals('(') && str.charAt(i) != ')') ||
    (pop.equals('[') && str.charAt(i) != ']') ||
    (pop.equals('{') && str.charAt(i) != '}')) {

您也可以使用原始char 作为pop 的类型,而只需使用普通的==,例如char pop = stk.pop(); if (pop == '(' || ....


正如我在上面的评论中指出的,您可以使用字符串检查字符是否在字符列表中:

if ("([{".indexOf(str.charAt(i)) >= 0) { ... }

您也可以在匹配检查中使用它:

int idx = ")]}".indexOf(str.charAt(i));
if (idx >= 0 && "([{".charAt(idx) != pop) {
  // They don't match!
}

【讨论】:

  • 我认为 OP 代码还有一个问题:考虑测试用例 "("; 'balanced 将保持正确;最终的正确性检查还应包括 stk.isEmpty()。跨度>
  • 感谢您的帮助!真的很感激。
  • @Ian 当然,那也是。在代码中没有那么远。
【解决方案2】:

已经解决了弹出和空堆栈的问题。您还可以考虑将括号字符与检查代码分开,并将该代码放在单独的方法中:

import java.util.*;

    public class BracketCheck
    {
       public static void main(String[] args) throws Exception
       {
          Map<Character, Character> brackets = new Hashtable<>();
          brackets.put(']', '[');
          brackets.put('}', '{');
          brackets.put(')', '(');


          Scanner s = new Scanner(System.in);

          System.out.println("Enter a string");

          System.out.format("balanced: %b%n", isBalanced(s.nextLine(), brackets));
       }

       public static boolean isBalanced(String str, Map<Character, Character> brk)
       {
          Stack<Character> stk = new Stack<>();

          for (char c : str.toCharArray())
          {
             if (brk.containsValue(c))
             {
                stk.push(c);
             }
             else
             {
                if (brk.containsKey(c))
                {
                   if (stk.isEmpty() || !brk.get(c).equals(stk.pop()))
                   {
                      return false;
                   }
                }
             }
          }

          return stk.isEmpty();
       }
    }

【讨论】:

    猜你喜欢
    • 2022-01-02
    • 2021-12-11
    • 2023-04-08
    • 1970-01-01
    • 1970-01-01
    • 2022-01-07
    • 2016-06-26
    • 2017-06-10
    • 2022-01-10
    相关资源
    最近更新 更多