以下代码使用堆栈标识平衡括号有什么问题
What is wrong with the following code to identify balanced parentheses using stack?
问题:
给定一个由括号组成的序列,确定表达式是否平衡。如果每个左括号都可以与前者之后出现的闭括号唯一配对,则括号序列是平衡的。此外,它们之间的间隔必须平衡。您将获得三种类型的括号:(、{ 和 [.
{[()]} - 这是一个平衡括号。
{[(])} - 这不是一个平衡括号。
输入格式:
*输入的第一行包含测试用例的数量。
*每个测试用例由一行和括号序列组成。
stack <char> stk;
int main() {
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
int n;
cin>>n;
for(int i=0;i<n;i++)
{
string s;
cin>>s;cout<<s;
int j=0;
while(j!=s.length())
{
if(stk.size()==0&&(s[j]==')'||s[j]==']'||s[j]=='}'))
{stk.push('z');}
if(s[j]=='('||s[j]=='['||s[j]=='{')
stk.push(s[j]);
if(stk.top()=='('&&s[j]==')')
stk.pop();
if(stk.top()=='['&&s[j]==']')
stk.pop();
if(stk.top()=='{'&&s[j]=='}')
stk.pop();
j++;
}
if(stk.size()==0)
cout<<"YES"<<endl;
else
{
cout<<"NO"<<endl;
while(stk.size()!=0)
stk.pop();
}
}
return 0;
}
它是用于检查平衡括号的代码。它对以"{"开头的字符串工作正常,但对"[]"等字符串失败
您一定是遇到了分段错误。
假设
s = "[]";
第一次迭代后,您的堆栈仅包含 "["。
在第二次迭代期间,
if(stk.top()=='['&&s[j]==']')
stk.pop();
上面的代码使您的堆栈为空。在下一行中,您要呼叫
stk.top() // But your stack is empty
在
if(stk.top()=='{'&&s[j]=='}')
stk.pop();
这就是问题所在。所以在打电话之前
stk.top();
确保您的堆栈不为空。
查看有关平衡括号的本教程。
相关文章:
- 警告处理为错误这里有什么问题
- C++我的数学有什么问题,为什么我的代码不能正确循环
- 当我尝试添加 2 个大字符串时,我无法弄清楚出了什么问题
- 违反const正确性:我应该现实地期待什么问题
- 这个带有模板<类 Vector 的C++代码片段有什么问题>
- 我的逻辑反转字符串中的元音有什么问题?
- 需要以下代码的帮助,下面的代码有什么问题
- 常量公共成员有什么问题?
- 以下代码中的函数模板有什么问题?
- 这个返回元素位置的基于循环的函数有什么问题?
- creat_list2功能有什么问题?
- 格式说明符C++有什么问题
- 任何人都可以告诉我我的 C++ 代码出了什么问题?
- 从 argv[1] 转换为字符 * 字符串后有什么问题?
- 我的堆栈和库存清单程序的结构有什么问题?
- 此工厂功能有什么问题?
- 以下 C++ 代码有什么问题?
- 数组为此合并排序函数提供了正确的输出,但向量给出了不正确的输出.出了什么问题?
- reinterpret_cast,只读访问,简单的可复制类型,会出什么问题?
- 它解决了什么问题,对于非真空初始化,生命周期在初始化之前就开始了