Java:使用堆栈

时间:2018-01-21 19:20:06

标签: java string char stack

在这个程序中,我试图检查输入字符串中的括号是否平衡。例如,(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");
        }
    }
}

2 个答案:

答案 0 :(得分: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!
}

答案 1 :(得分:0)

已经解决了pop和empty stack的问题。您还可以考虑将支架字符与检查代码分开,并将该代码放在单独的方法中:

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