描述
现在,有一行括号序列,请你检查这行括号是否配对。
-
输入
- 第一行输入一个数N(0<N<=100),表示有N组测试数据。后面的N行输入多组输入数据,每组输入数据都是一个字符串S(S的长度小于10000,且S不是空串),测试数据组数少于5组。数据保证S中只含有"[","]","(",")"四种字符 输出
- 每组输入数据的输出占一行,如果该字符串中所含的括号是配对的,则输出Yes,如果不配对则输出No 样例输入
-
3 [(]) (]) ([[]()])
样例输出
-
No No Yes
分析:
该题目使用栈来实现,使用stl中的stack实现,注意使用stack时的注意事项:
1.
清除stack里面的数据的时候,只能使用while循环,判断只要非空,就要出栈
2.
使用st.top()函数的时候,一定要先判断st为非空,不然会出现runtime error
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <vector>
#include <set>
#include <map>
#include <stack>
#include <string>
using namespace std;
int main()
{
int n;
cin >> n;
string s;
stack<char>st;
while(n--)
{
cin >> s;
while(!st.empty())
st.pop();
for(int i = 0;i < s.length();i++)
{
if(s[i] == '('||s[i] == '[')
st.push(s[i]);
else if(s[i] == ')'||s[i] == ']')
{
if(s[i] == ')'&&!st.empty()&&st.top() == '(')
st.pop();
else if(s[i] == ']'&&!st.empty()&&st.top() == '[')
st.pop();
else
st.push(s[i]);
}
}
if(st.empty())
cout << "Yes" << endl;
else
cout << "No" << endl;
}
return 0;
}