首页 > 其他 > 详细

Problem A 栈

时间:2015-07-22 22:13:19      阅读:180      评论:0      收藏:0      [点我收藏+]

Description

 

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. Your program 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 string a line.

 

Output 

A sequence of Yes or No on the output file.

 

Sample Input 

 

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

 

Sample Output 

Yes
No
Yes
分析:
这个括号配对问题很符合后进先出-栈的方法,遇到左括号时进栈,遇到右括号时将栈顶元素与之配对的括号出栈。

 

#include <iostream>
#include <stack>
using namespace std;
int main()
{
	int n;
	cin >> n;
	cin.get();
	while (n--)
	{
		stack<char>st_ch;
		int loge = 1;
		char c;
		while (cin.get(c) && c != \n)
		{
			if (c == ‘)‘)
			{
				if (st_ch.empty())
					loge = 0;
				else if (st_ch.top() == ‘(‘)
					st_ch.pop();
				else
					loge = 0;
			}
			else if (c == ‘]‘)
			{
				if (st_ch.empty())
					loge = 0;
				else if (st_ch.top() == ‘[‘)
					st_ch.pop();
				else
					loge = 0;
			}
			else
				st_ch.push(c);
		}
		if (st_ch.empty()&&loge)
			cout << "Yes" << endl;
		else
			cout << "No" << endl;

	}
	return 0;

}

Problem A 栈

原文:http://www.cnblogs.com/xl1164191281/p/4668703.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!