E - Parentheses Balance

本文介绍了一个使用栈数据结构实现的括号匹配算法。该算法能够判断由圆括号'()'和方括号'[]'组成的字符串是否正确配对。通过逐个读取字符并利用栈进行匹配检查,程序能高效地确定输入字符串的有效性。

E - Parentheses Balance




You are given a string consisting of parentheses () and []. A string of this type is said to be correct:

(a) if it is the empty string

(b) if A and B are correct, AB is correct,

(c) if A is correct, (A) and [A] is correct.

Write a program that takes a sequence of strings of this type and check their correctness. Yourprogram can assume that the maximum string length is 128.

Input

The file contains a positive integer n and a sequence of n strings of parentheses ‘()’ and ‘[]’, one stringa line.

Output

A sequence of ‘Yes’ or ‘No’ on the output file.

Sample Input

3

([])

(([()])))

([()[]()])()

Sample Output

Yes

No

Yes





代码:

#include<iostream>
#include<cstdio>
#include<stack>
using namespace std;

int main(void)
{
	stack<char> p;
	int i,j,n;
	scanf("%d",&n);
	getchar();
	while(n--)
	{
		string s1;
		getline(cin,s1);//(a) if it is the empty string
		int len=s1.length();
		for(i=0;i<len;i++)
		{
			if(p.empty())
			{
				p.push(s1.at(i));
				continue;
			}
			if((p.top()=='('&&s1.at(i)==')')||(p.top()=='['&&s1.at(i)==']'))
			{
				p.pop();
				continue;
			}
			else
			p.push(s1.at(i));
		}
		if(p.empty())
		printf("Yes\n");
		else
		printf("No\n");
		while(!p.empty())
		{
			p.pop();
		}
		s1="";
	}
	return 0;
}


 
Description D a r k D a w n 在乐学上出了一道给定括号序列,判断其合法性的问题。 括号序列是由左括号“(”和右括号“)”组成的非空序列。对于一个括号序列很容易判定其合法性。比如“()”、“(())()”、“(()())”、“(()(()))”、“()()()”都是合法的,而“)”、“(”、“(()”、“(()))(”都是非法的。 R o a r k 看了一眼题,立刻去饮水机处接了一杯水。 D a r k D a w n 意识到他是在暗示这道题太水了,于是立刻把题改了改,增加了一、、难度。 给定  n  个括号序列,两两配对,问最多能组成多少对合法括号序列。(每一个括号序列只能在一对中出现) R o a r k 接完水回来再看了看新题,开始挠头了,快帮帮他! Input 第一行输入整数  n  左小括号 斜体字 1 斜体字 小于等于 n 斜体字 小于等于 斜体字 100000 右小括号  表示有  n  个括号序列。 接下来  n  行,每行输入一个只由“(”和”)“构成的字符串  s 下标 i  。(字符串长度满足 1 小于等于 左 绝对值 s 下标 i 右 绝对值 小于等于 1 e 5 ) 所有字符串长度总和满足 开始样式 行内 结束样式 开始样式 显示 结束样式 加总 从 i 对 左 绝对值 s 下标 i 右 绝对值 小于等于 5 e 5 。 Output 输出一个整数,表示最大的合法括号序列对数。 Hint 第一组用例可以组成2对合法括号序列,分别是“((   )())”、“(   )”。  测试输入  期待的输出  时间限制  内存限制  额外进程  测试用例 1 以文本方式显示 1. 7↵ 2. )())↵ 3. )↵ 4. ((↵ 5. ((↵ 6. (↵ 7. )↵ 8. )↵ 以文本方式显示 1. 2↵
最新发布
09-11
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值