码迷,mamicode.com
首页 > 其他好文 > 详细

Problem A 栈

时间:2015-07-22 22:14:56      阅读:138      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!