NYOJ 2 括号配对问题(栈)

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 )
 

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值