描述
现在,有一行括号序列,请你检查这行括号是否配对。
-
输入
- 第一行输入一个数N(0<N<=100),表示有N组测试数据。后面的N行输入多组输入数据,每组输入数据都是一个字符串S(S的长度小于10000,且S不是空串),测试数据组数少于5组。数据保证S中只含有"[","]","(",")"四种字符 输出
- 每组输入数据的输出占一行,如果该字符串中所含的括号是配对的,则输出Yes,如果不配对则输出No
-
样例输入
-
3 [(]) (]) ([[]()])
样例输出
-
No No Yes
用栈实现的,VS2013 和gcc version 4.8.2 (GCC)编译通过 NO error NO warning
不过还是不能AC RuntimeError o(╯□╰)o 。。。
写的很烂,只不过就一思路而已。
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define N 10000+10
char Str[N];
typedef char Type;
typedef struct StackRecord
{
int TopOfStack;
Type *A;
}ArrayStack, *Stack;
Stack InitSatck(Stack S, int size)
{
S->TopOfStack = -1;
S->A = (Type *) malloc(sizeof(Type)* size);
return S;
}
void PushStack(Stack S, Type ch)
{
S->A[++S->TopOfStack] = ch;
}
Type PopStack(Stack S)
{
return S->A[S->TopOfStack--];
}
void DistoryStack(Stack S)
{
free(S->A);
free(S);
}
int main()
{
int i, n;
scanf("%d\n", &n);
while (n--)
{
gets(Str);
if (Str[0] == ']' || Str[0] == ')')
printf("No\n");
else
{
int flag = 1;
Stack S;
S = (Stack)malloc(sizeof(ArrayStack));
S = InitSatck(S, strlen(Str));
for (i = 0; i < strlen(Str); i++)
{
if (Str[i] == '[' || Str[i] == '(')
PushStack(S, Str[i]);
if (Str[i] == ']' || Str[i] == ')')
{
switch (Str[i])
{
case ']':
if (PopStack(S) != '[')
flag = 0;
break;
case ')':
if (PopStack(S) != '(')
flag = 0;
break;
}
}
}
if (flag && S->TopOfStack == -1)
printf("Yes\n");
else
printf("No\n");
DistoryStack(S);
}
}
return 0;
}
2015/9/17 update
#include<algorithm>
#include<iostream>
#include<cstdlib>
#include<cstring>
#include<cstdio>
#include<vector>
#include<stack>
#include<set>
using std::set;
using std::sort;
using std::pair;
using std::swap;
using std::stack;
using std::multiset;
#define pb(e) push_back(e)
#define sz(c) (int)(c).size()
#define mp(a, b) make_pair(a, b)
#define all(c) (c).begin(), (c).end()
#define iter(c) decltype((c).begin())
#define cls(arr, val) memset(arr, val, sizeof(arr))
#define cpresent(c, e) (find(all(c), (e)) != (c).end())
#define rep(i, n) for(int i = 0; i < (int)n; i++)
#define tr(c, i) for(iter(c) i = (c).begin(); i != (c).end(); ++i)
const int N = 10010;
const int INF = 0x3f3f3f3f;
typedef unsigned long long ull;
char buf[N];
bool solve() {
char x;
stack<char> op;
int n = strlen(buf);
rep(i, n) {
char &ch = buf[i];
if ('(' == ch || '[' == ch) op.push(ch);
else if (')' == ch) {
if (!op.size()) return false;
x = op.top();
if ('(' == x) op.pop();
else op.push(x);
} else if (']' == ch) {
if (!op.size()) return false;
x = op.top();
if ('[' == x) op.pop();
else op.push(x);
}
}
return op.empty();
}
int main() {
#ifdef LOCAL
freopen("in.txt", "r", stdin);
freopen("out.txt", "w+", stdout);
#endif
int t;
scanf("%d", &t);
getchar();
while (t--) {
gets(buf);
puts(solve() ? "Yes" : "No");
}
return 0;
}