Java自定义栈实现括号平衡校验输出错误原因排查
自定义栈括号校验问题修复说明
核心错误点
你的自定义栈实现存在4个逻辑问题,和Java官方Stack的行为不一致,导致校验结果错误:
- top指针未初始化:int类型成员变量默认初始值为0,但你
isEmpty()方法判断栈空的条件是top == -1,初始状态下栈明明是空的,但isEmpty()会返回false,逻辑完全错位。 - push、pop逻辑顺序混乱:你push时先移动top指针再赋值,pop时却先移动top指针再取值,导致取出的元素永远是栈顶的前一个元素,括号匹配完全错误。
- pop方法边界判断错误:原有判断条件
top > 0会导致栈只剩1个元素(top值为0)时无法弹出,匹配成功的括号无法正常出栈。 - peek方法无空校验:栈空时调用
peek()会直接触发数组越界异常,属于严重安全隐患。 - 额外问题:栈容量固定为10,若输入字符串的左括号数量超过5对会导致push失败,校验逻辑失效。
修复后的完整代码
import java.util.Scanner; public class Stack { int top; char []a = new char[100]; // 扩容到100避免常规测试用例溢出 // 新增构造函数初始化top指针 public Stack() { top = -1; } public void push(char c) { if(top < a.length - 1) { top++; a[top] = c; } } public char pop() { // 修正边界判断和取值逻辑 if(top >= 0) { char c = a[top]; top--; return c; } return 0; } public boolean isEmpty() { return (top == -1); } public char peek() { // 新增空校验 if(isEmpty()) { return 0; } return a[top]; } void displayStack() { for(int i = 0; i <= top; i++) System.out.print(a[i] + " "); } // 括号平衡校验方法 public static boolean CheckParentesis(String str) { if (str.isEmpty()) return true; Stack stack = new Stack(); for (int i = 0; i < str.length(); i++) { char Symbol = str.charAt(i); if (Symbol == '{' || Symbol == '(' || Symbol == '[') { stack.push(Symbol); continue; } if (Symbol == '}' || Symbol == ')' || Symbol == ']') { if (stack.isEmpty()) return false; char last = stack.peek(); if ((Symbol == '}' && last == '{') || (Symbol == ')' && last == '(') || (Symbol == ']' && last == '[')) stack.pop(); else return false; } } return stack.isEmpty(); } public static void main(String[] args) { Scanner sc = new Scanner(System.in); int count = sc.nextInt(); String[] str = new String[count]; sc.nextLine(); for (int i = 0; i < str.length; i++) { str[i] = sc.nextLine(); } for(String s: str) { if(CheckParentesis(s)) System.out.println("TRUE"); else System.out.println("FALSE"); } } }
修复后运行你给出的测试用例,输出结果和预期完全一致。
内容的提问来源于stack exchange,提问作者Mahesh Divate
相关产品推荐
相关产品推荐

