C++ 使用testcases时输出不正确,否则它将';s工作正常(使用了堆叠)
下面我上传了一个代码来检查字符串中是否有括号是平衡的或没有使用堆栈。它对1个输入有效,但对多个测试用例来说,正确的输出无效。请帮助。提前感谢C++ 使用testcases时输出不正确,否则它将';s工作正常(使用了堆叠),c++,stack,destructor,testcasesource,C++,Stack,Destructor,Testcasesource,下面我上传了一个代码来检查字符串中是否有括号是平衡的或没有使用堆栈。它对1个输入有效,但对多个测试用例来说,正确的输出无效。请帮助。提前感谢 int main() { int t; cin >>t; cin.ignore(); while(t--) { { stack s; char *st; st=new char[100]; g
int main()
{
int t;
cin >>t;
cin.ignore();
while(t--)
{
{
stack s;
char *st;
st=new char[100];
gets(st);
s.create(strlen(st));
if(!count_elem(st))//counts if the brackets are in pairs or not
cout << "NO" <<endl;
else
func1(s,st);
}
}
return 0;
}
void func1(stack s,char *st)
{
static int i=0,flag=0;
// printf("%d %d\n",i,flag);
if(st[i]=='(' || st[i]=='{' || st[i]=='[')
{
flag=1;
s.push(st[i]);
}
else
{
if(s.isEmpty())
flag=0;
else
{
if(st[i]=='}')
{
//printf("%c\n",s.get_top());
if(s.get_top()=='{')
{
flag=1;
s.pop();
}
else
flag=0;
}
if(st[i]==')')
{
//printf("%c\n",s.get_top());
if(s.get_top()=='(')
{
flag=1;
s.pop();
}
else
flag=0;
}
if (st[i]==']')
{
//printf("%c\n",s.get_top());
if(s.get_top()=='[')
{
flag=1;
s.pop();
}
else
flag=0;
}
}
}
i++;
if(flag==1)
{
if(i<strlen(st))
func1(s,st);
else
cout << "YES"<<endl;
}
else
cout << "NO"<< endl;
}
intmain()
{
int t;
cin>>t;
cin.ignore();
而(t--)
{
{
堆栈s;
char*st;
st=新字符[100];
获取(st);
s、 创建(strlen(st));
if(!count_elem(st))//计算括号是否成对
问题是…当程序从一个测试用例转到另一个测试用例时,它不会重新初始化i=0,flag=0…因为它们被声明为静态变量。相反,可以做的是…声明i,全局标记…并在对每个测试用例进行第一次func()调用之前分配i=0;flag=0
int main()
{
int t;
cin >>t;
cin.ignore();
while(t--)
{
{
stack s;
char *st;
st=new char[100];
gets(st);
s.create(strlen(st));
if(!count_elem(st))
cout << "NO" <<endl;
else
{
i=0;
flag=0;
func1(s,st);
}
delete []st;
}
}
return 0;
}
intmain()
{
int t;
cin>>t;
cin.ignore();
而(t--)
{
{
堆栈s;
char*st;
st=新字符[100];
获取(st);
s、 创建(strlen(st));
如果(!计数元素(st))
什么样的测试用例失败了?第一个测试用例总是正确的,但它只是显示了后面所有其他测试用例的一些随机输出。第一个,呃?我不是问你有多少测试失败了,我不是问你以什么顺序运行通过和失败的测试,我是问一个失败的测试用例。投票结束。