天天看点

括号匹配

括号配对问题

时间限制:3000 ms | 内存限制:65535 kb

难度:3

描述

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

输入

第一行输入一个数n(0<n<=100),表示有n组测试数据。后面的n行输入多组输入数据,每组输入数据都是一个

字符串s(s的长度小于10000,且s不是空串),测试数据组数少于5组。数据保证s中只含有"[","]","(",")"四种字符

输出

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

样例输入

3

[(])

(])

([[]()])

样例输出

no

yes

代码如下:

测试已经accerted!

#include <iostream>

#include <string>

using namespace std;

int main()

{

int testnum;

stack<char> brackets;

cin >> testnum;

cin.get();//吸收回车符

for (int test = 1; test <= testnum; test++)

string buf;

cin >> buf;

int len = buf.size();

for (int i = 0; i < len-1; i++)

if ((buf[i] == '[' && buf[i+1] == ']') || (buf[i] == '(' && buf[i+1] == ')'))

buf.erase(i, 2);

len = buf.size();

i -= 3;//注意这里,删除匹配的一对之后,只要后退两个位置就可以判断

}

else

continue;

if (len == 0)

cout << "yes" << endl;

cout << "no" << endl;

}//for

return 0;