括号配对问题

描述

现在,有一行括号序列,请你检查这行括号是否配对。

输入

第一行输入一个数N(0<N<=100),表示有N组测试数据。后面的N行输入多组输入数据,每组输入数据都是一个字符串S(S的长度小于10000,且S不是空串),测试数据组数少于5组。数据保证S中只含有"[","]","(",")"四种字符

输出

每组输入数据的输出占一行,如果该字符串中所含的括号是配对的,则输出Yes,如果不配对则输出No

样例输入

3

[(])

(])

([])

样例输出

No

No

Yes

代码如下:

#include<iostream>
#include<string>
#include<stack>
#include<vector>
using namespace std;

int main()
{
	string s;	//输入的括号串
	vector<string>vs;
	int N;
	cin >> N;
	int iCount = 0;
	while (cin >> s && iCount != N){
		vs.push_back(s);	//将所有输入的字符串暂时保存到vector中
		++iCount;
	}
	for (int index = 0; index != vs.size(); ++index){
		stack<char>sc;	//每检索一个vector元素,都要将栈清空
		sc.push(vs[index][0]);	//第一个元素肯定要入栈,vs[index]获取当前的字符串
		if (vs[index].size() > 1){	//只考虑输入的括号的个数大于1的情况,因为只有一个括号的字符串肯定不匹配
			for (int i = 1; i != vs[index].size(); ++i){	//遍历当前字符串除第一个字符外的所有字符
				if (!sc.empty()){	//为避免执行出栈操作时可能会对空栈进行操作,故先检查栈是否为空
					if ((sc.top() == '[' && vs[index][i] == ']') ||	
						sc.top() == '(' && vs[index][i] == ')')	//若匹配,将栈顶元素出栈
						sc.pop();
					else
						sc.push(vs[index][i]);	//否则,将当前字符入栈
				}
				else
					sc.push(vs[index][i]);	//若栈为空,则入栈
			}
		}
		else    //如果只有一个括号,肯定不匹配
			cout << "No" << endl;
		if (sc.empty())	//若最后栈为空,则说明完全匹配
			cout << "Yes" << endl;
		else    //否则不匹配
			cout << "No" << endl;	
	}
}

题目原地址:
http://acm.nyist.net/JudgeOnline/problem.php?pid=2

posted @ 2016-12-01 20:16  larryking  阅读(190)  评论(0编辑  收藏  举报