• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录

  • 博客园
  • 联系
  • 订阅
  • 管理

View Post

Problem A 栈

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;

}

posted on 2015-07-22 21:31  tony-cao  阅读(164)  评论(0)    收藏  举报

刷新页面返回顶部
 
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3