栈实现括号匹配函数仅单右括号测试用例失败,求修改方案
Fixing the Single Closing Bracket Issue in Your Bracket Matching Code
Let's break down why your code fails when the input is just ')':
- When you get a closing bracket like
')', your code only processes it if the stack isn't empty. But if the input starts with a closing bracket, the stack is empty, so this code skips processing it entirely. At the end, the stack is still empty, so your function incorrectly returnstrue—even though there's no matching opening bracket.
Plus, there's another hidden issue: when you encounter a mismatched pair (like stack top is '[' but you get ')'), your code just continues instead of immediately returning false. This lets invalid pairs slip through, which will also cause wrong results in other edge cases.
Here's the revised code with fixes:
bool areBracketsBalanced(char exp[]) { int len = strlen(exp); stack<char> s; for(int i=0;i<len;i++){ char ch = exp[i]; if(ch=='(' || ch=='[' || ch=='{'){ s.push(ch); } else if(ch==')'){ // If stack is empty, no matching '(' exists if(s.empty() || s.top()!='('){ return false; } s.pop(); } else if(ch==']'){ if(s.empty() || s.top()!='['){ return false; } s.pop(); } else if(ch=='}'){ if(s.empty() || s.top()!='{'){ return false; } s.pop(); } else{ // Ignore non-bracket characters if needed, or handle as invalid continue; } } // Only return true if stack is empty (all opening brackets matched) return s.empty(); }
Key changes made:
- For every closing bracket, first check if the stack is empty—if it is, immediately return
false(since there's no corresponding opening bracket). - Combine the "mismatched bracket" check with the empty stack check. If either condition is true, return
falseright away instead of continuing (this stops processing as soon as an invalid state is found, which is more efficient too). - Simplified the final return statement to directly return
s.empty()for cleaner code.
This will correctly handle the ')' case: when the loop processes ')', it sees the stack is empty and returns false immediately, which is the correct behavior.
内容的提问来源于stack exchange,提问作者NAMAN VERMA
相关产品推荐
相关产品推荐

