# 南阳理工ACM 2括号配对问题

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

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

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

3
[(])
(])
([[]()])

No
No
Yes

网络

naonao

# include <stdio.h>
# include <string.h>

int main (void)
{
char Stack[10000], str[10000];
int N, j;
scanf ("%d\n", &N);
while (N--)
{
int flag = 0, i = 0;
gets(str);
for (i = 0; i < strlen(str); i++)
{
if (str[i]== '(' || str[i] == '[')
{
Stack[j++] = str[i];
}
else
{
if(j==0)
{
flag = 1;
break;
}
j--;
if ((Stack[j]== '(' && str[i]!=')')||(Stack[j]== '[' && str[i]!=']'))
{
flag = 1;
break;
}
}
}
if (flag == 1 || j==0)
printf ("No\n");
else
printf ("Yes\n");

}
return 0;
}

#include <stdio.h>

#include <stdlib.h>

struct Stack
{
char *base;
char *top;
int sizestack;
};

void InitStack (struct Stack &S)
{
S.base = (char *)malloc (sizeof(char)*10010);
S.top = S.base;
int sizestack = 10002;
}

void Push (struct Stack &S, char c)
{
*S.top++ == c;
}
int StackEmp (struct Stack S)
{
if (S.top == S.base)
return 1;
else
return 0;
}

void Pop (struct Stack &S, char &c)
{
c = *--S.top;
}

int main (void)
{
Stack S;
InitStack(S);
int N = 0, flag = 0;
char str[10010], *p, s;
scanf ("%d\n", &N);
while (N--)
{
flag = 0;
gets(str);
p = str;
while (*p != '\0')
{
if (*p == '(' || *p == '[')
Push(S, *p);
else
{
if (StackEmp(S))
{
flag = 1;
break;
}
else
{
Pop(S, s);
if ((s == '(' && *p != ')') || (s == '[' && *p != ']'))
{
flag = 1;
break;
}
}
}
p++;
}

if (flag == 1 || !StackEmp(S))
printf ("No\n");
else
printf ("Yse\n");
S.top = S.base;

}
free(S.base);
S.base = S.top = NULL;
return 0;
}