题目
There are n brackets, and Skylar want to know whether they are matched. The brackets will only contain {, }, (, ), [, ]. Here is the matching rules. For example, {{[}]} is not matching, but [{{}}()] is matching. Please write a program to check whether the given string is matched or not.
就是左右括号匹配的题
输入
The first line will be an integer T(1≤T≤10)T(1≤T≤10), which is the number of test cases.
For each test case, the first line will be an integer n(1≤n≤30000)n(1≤n≤30000).
Then there is a line with nn brackets.
输出
For each test case, print YES if the test case is a matching case. Otherwise, print NO
样例
7
1
(
2
()
2
{]
6
[(){}]
4
(])[
8
[[{{}}]]
6
[][{]]
样例输出
NO
YES
NO
YES
NO
YES
NO
C++实现代码
#include <cstdio>
#include <cstring>
#include <iostream>
class ArrayStack{
public:
char *arr;//数组?
int count=0;
~ArrayStack()
{
if (arr)
{
delete[] arr;
arr = NULL;
}
}
ArrayStack(int n=3000) //这里面就是比普通的
{ arr = new char[n];
}
void push(char t) {
arr[count++] = t;
}
void pushAll(char* t,int n) {
memcpy(arr,t,n*sizeof(char));
count=n;
}
char peek(){
return arr[count-1];
}
char pop(){
int ret = arr[count-1];
count--;
return ret;
}
};
void easyFunction( char* input,int n,std::string &result);
int main(){
int times;
scanf("%d",×);
std::string result[times];
for (int i = 0; i < times; ++i) {
int n;
scanf("%d",&n);
char inut[n];
std::cin>>inut;
easyFunction(inut,n,result[i]);
}
for (int j = 0; j < times; ++j) {
std::cout<<result[j]<<std::endl;
}
}
void easyFunction( char* input,int n,std::string& result){
int isMatch=0;
ArrayStack* arrayStack=new ArrayStack(n);
for (int i = 0; i <n; ++i) {
char Demo=*(input+i);
switch (Demo) {
case '(':
arrayStack->push(Demo);
break;
case '[':
arrayStack->push(Demo);
break;
case '{':
arrayStack->push(Demo);
break;
case ']': {
if (arrayStack->count==0){
result="NO";
return;
}
char ch = arrayStack->pop();
if (ch == '[') {
break;
} else {
result="NO";
return;
}
}
case '}': {
if (arrayStack->count==0){
result="NO";
return;
}
char ch = arrayStack->pop();
if (ch == '{') {
break;
} else {
result="NO";
return;
}
}
case ')': {
if (arrayStack->count==0){
result="NO";
return;
}
char ch = arrayStack->pop();
if (ch == '(') {
break;
} else {
result="NO";
return;
}
}
}
}
if (arrayStack->count==0)result="YES";
else result="NO";
}