C#括号有效性检查函数运行无输出,需如何修改?
括号有效性检查函数的问题与修正
问题描述
我编写了一个C#函数用于检查字符串中括号是否有效,有效返回true,无效返回false。示例如下:
- str1:
{ [ a + b ] - ] ( c - d } ]→ 返回false - str2:
{ [ a + b ] - ( c - d ) }→ 返回true
但运行程序后没有任何输出,仅显示空白,请问需要修改哪些内容?
原代码
主检查函数
public static Boolean BracketCheck(string str) { Stack<char> stk = new Stack<char>(); Stack<char> aid = new Stack<char>(); Stack<char> temp = new Stack<char>(); while (str != "") { char ch = str[0]; if(ch == '(' || ch == '{' || ch == '[' || ch == ')' || ch == '}' || ch == ']') { stk.Push(ch); } if(str.Length != 1) str = str.Substring(1, str.Length - 1); } stk = Opposite(stk); char first = stk.Pop(); char last; while (!stk.IsEmpty() && !aid.IsEmpty()) { while (!stk.IsEmpty()) { aid.Push(stk.Top()); last = stk.Pop(); if (stk.IsEmpty()) if (int.Parse(first + "") + 1 != int.Parse(last + "") || int.Parse(first + "") + 2 != int.Parse(last + "")) { return false; } } first = aid.Pop(); while (!aid.IsEmpty()) { aid.Push(aid.Top()); last = aid.Pop(); if (aid.IsEmpty()) if (int.Parse(first + "") + 1 != int.Parse(last + "") || int.Parse(first + "") + 2 != int.Parse(last + "")) { return false; } } first = stk.Pop(); } return true; }
栈反转函数
public static Stack<char> Opposite(Stack<char> stk) { Stack<char> temp = new Stack<char>(); while (stk.IsEmpty()) { temp.Push(stk.Pop()); } return temp; }
问题分析与修改点
1. 字符串处理死循环
原代码中,当str长度为1时,不会执行截取操作,导致str始终不为空,进入死循环,程序卡住无输出。
- 修改:将循环条件改为
str.Length > 0,且无论字符串长度如何都执行截取,避免死循环。
2. 栈反转函数逻辑错误
Opposite函数的循环条件是stk.IsEmpty(),意味着只有栈为空时才执行循环,完全无法实现栈反转,最终返回空栈。后续执行stk.Pop()会抛出异常,导致程序崩溃无输出。
- 修改:将循环条件改为
!stk.IsEmpty(),正确反转栈。
3. 括号匹配逻辑完全错误
原代码的匹配逻辑不符合括号有效性规则(正确规则:左括号入栈,右括号匹配栈顶左括号,不匹配直接返回false;遍历结束后栈为空则有效),仅简单比较首尾括号,无法处理嵌套、顺序错误的情况。
- 修改:重构为标准的栈匹配逻辑。
4. 字符转ASCII的错误写法
int.Parse(first + "")会在字符非数字时抛出异常,正确获取字符ASCII值应使用(int)first。
5. 辅助栈逻辑混乱
原代码中aid栈初始为空,导致外层循环直接跳过,无法完成匹配检查。
修正后的代码
public static bool BracketCheck(string str) { Stack<char> stack = new Stack<char>(); // 遍历字符串每个字符 foreach (char ch in str) { // 遇到左括号,入栈 if (ch == '(' || ch == '[' || ch == '{') { stack.Push(ch); } // 遇到右括号,检查匹配 else if (ch == ')' || ch == ']' || ch == '}') { // 栈为空,说明无对应左括号,直接返回false if (stack.Count == 0) { return false; } char top = stack.Pop(); // 检查当前右括号是否与栈顶左括号匹配 if (!IsMatchingPair(top, ch)) { return false; } } // 非括号字符,直接跳过 } // 遍历结束后,栈为空说明所有括号都匹配,否则存在未闭合的左括号 return stack.Count == 0; } // 辅助函数:判断左右括号是否匹配 private static bool IsMatchingPair(char left, char right) { return (left == '(' && right == ')') || (left == '[' && right == ']') || (left == '{' && right == '}'); }
说明
修正后的代码采用标准栈匹配逻辑:
- 遍历字符串,左括号入栈;
- 遇到右括号时,若栈空直接返回
false,否则弹出栈顶左括号检查匹配; - 遍历完成后,栈为空则所有括号正确闭合,返回
true,否则返回false。
内容的提问来源于stack exchange,提问作者schnitzel_prog
相关产品推荐
相关产品推荐

