您的位置:首页 > 其它

NYOJ 2题 括号配对问题

2012-04-04 00:52 337 查看
http://acm.nyist.net/JudgeOnline/problem.php?pid=2

1、我的代码:

#include <iostream>
#include <cstring>
using namespace std;

#define MAXSIZE 10005
int main(void)
{
int k;
cin >> k;
while(k--)
{
char str[MAXSIZE];
cin >> str;
char stack[MAXSIZE];
int len = strlen(str);
int j = 0;
bool tag = true;
for(int i = 0; i < len; i++)
{
switch(str[i])
{
case '(' :
case '[' :
stack[j++] = str[i];
break;
case ')' :
if( stack[j - 1] == '(' )
{
tag = true;
j--;
}
else
tag = false;
break;
case ']' :
if( stack[j - 1] == '[' )
{
tag = true;
j--;
}
else
tag = false;
break;
default : cout << "Error!" << endl;
}
if(tag == false)	//	NOTE
break;
}
if( tag == true && j == 0 )
cout << "Yes" << endl;
else
cout << "No" << endl;
}

return 0;
}


2、时间,内存,长度最优代码:

#include<stdio.h>
int main()
{
int t;
char c,s[10001],*p;
scanf("%d\n",&t);
while(t--){
*s=getchar();
p=s+1;
while((c=getchar())!='\n'){
if(*(p-1)==c-1||*(p-1)==c-2)
p--;
else
*p++=c;
}
if(p==s)
printf("Yes\n");
else
printf("No\n");
}
}


3、标程:

#include<iostream>
#include<vector>
#include<string>
using namespace std;
int main()
{
int n;
cin>>n;
while(n--)
{
vector<char> vec;
string ch;
vec.push_back(' ');
cin>>ch;
for(int i=0;i<ch.length();i++)
{
vec.push_back(ch[i]);
if( vec.back()-1 == *(vec.end()-2) || vec.back()-2 == *(vec.end()-2))
{
vec.pop_back();
vec.pop_back();
}
}
if(vec.size()==1)
cout<<"Yes"<<endl;
else
cout<<"No"<<endl;
}
return 0;
}


(我用栈的代码提交总是WA,不知道为什么,见 http://blog.csdn.net/justme0/article/details/7415337
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: