UVA673 Parentheses Balance

题目链接: http://acm.hust.edu.cn/vjudge/contest/view.action?cid=43041#problem/E

题目大意:给你一个字符串,让你判断是否能将里面的括号按照顺序配对,例如(){},或者(()[]),但像([)]这样就是不可以的。

解题思路:建立一个栈,碰到左括号就进栈,右括号则出栈并匹配。

题目坑点:

1.注意到空字符串了没?

2.出栈之前判断是否为空栈了没?

3.字符串读完以后判断栈空了没?


代码如下:

#include <iostream>
#include <stdio.h>
#include <fstream>
#include <iomanip>
#include <cmath>
#include <string>
#include <string.h>
#include <sstream>
#include <cctype>
#include <climits>
#include <set>
#include <map>
#include <queue>
#include <vector>
#include <iterator>
#include <algorithm>
#include <stack>
#include <functional>
/*int类型最大值INT_MAX,short最大值为SHORT_MAX
long long最大值为LONG_LONG_MAX*/
//cout << "OK" << endl;
#define _clr(x) memset(x,0,sizeof(x))
using namespace std;
const int MAXN = 200;
const int INF = INT_MAX;
const double eps = 1e-8;
const double EULER = 0.577215664901532860;
const double PI = 3.1415926535897932384626;
const double E = 2.71828182845904523536028;
typedef long long LL;

int main()
{
    //freopen("sample.in", "r", stdin);
	//freopen("sample.out", "w", stdout);
	
	int t;
	cin >> t;
	cin.ignore(100,'\n');
	while(t--)
	{
		stack<char>x;
		string s;
		int p = 1;
		getline(cin,s);
		if(s == "") 
		{
			cout << "Yes" << endl;
			continue;
		}
		//cout << strlen(s) << endl;
		for(int i = 0;i<s.length();i++)
		{
			if(s[i] == '(' || s[i] == '[')
			x.push(s[i]);
			else
			{
				if(x.empty())
				{
					p = 0;
					break;
				}
				char ch = x.top();
				x.pop();
				if( (s[i] == ')' && ch != '(') || (s[i] == ']' && ch != '[') )
				{
					p = 0;
					break;
				}
			}
		}
		if(!x.empty())
		p = 0;
		if(p)
		cout << "Yes" << endl;
		else
		cout << "No" << endl;
	}

    //fclose(stdin);
    //fclose(stdout); 
    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值