【发布时间】:2020-02-04 20:43:57
【问题描述】:
我很困惑为什么我们需要检查堆栈是否为空?
因为如果例如,字符串没有任何类型或括号,那么我们将总是有 false ,这意味着字符串不平衡?
不能,我们甚至忽略了if(s.empty()) 并立即返回false,因为不会有任何东西被压入堆栈?
#include<bits/stdc++.h>
using namespace std;
// function to check if paranthesis are balanced
bool areParanthesisBalanced(string expr)
{
stack<char> s;
char x;
// Traversing the Expression
for (int i=0; i<expr.length(); i++)
{
if (expr[i]=='('||expr[i]=='['||expr[i]=='{')
{
// Push the element in the stack
s.push(expr[i]);
continue;
}
/*if (expr[i]=='}'||expr[i]=='}'||expr[i]=='}')
return false;
what about this alternative? */
// IF current current character is not opening
// bracket, then it must be closing. So stack
// cannot be empty at this point.
if (s.empty())
return false;
switch (expr[i])
{
case ')':
// Store the top element in a
x = s.top();
s.pop();
if (x=='{' || x=='[')
return false;
break;
case '}':
// Store the top element in b
x = s.top();
s.pop();
if (x=='(' || x=='[')
return false;
break;
case ']':
// Store the top element in c
x = s.top();
s.pop();
if (x =='(' || x == '{')
return false;
break;
}
}
// Check Empty Stack
return (s.empty());
}
// Driver program to test above function
int main()
{
string expr = "{()}[]";
if (areParanthesisBalanced(expr))
cout << "Balanced";
else
cout << "Not Balanced";
return 0;
}
【问题讨论】:
-
这只是一个糟糕的代码。:)
-
那有什么办法优化它?
-
...该行上方的评论没有准确解释您的要求吗?它清楚地解释了如果字符串中的字符不是左括号,那么它必须是右括号的期望。换句话说,这个函数需要一个只有左括号和右括号的字符串。因此,您的语句“what if 例如,字符串没有任何类型或括号”被简单地假定为错误 - 这将是传递给此函数的无效字符串。
-
一旦出现任何非括号字符,您的代码就会失败,例如'[x]',这是完美平衡的。
-
#include<bits/stdc++.h>-- 使用正确的标题,而不是这个。