673 - Parentheses Balance括号匹配
输入一些由小括号和中括号组成的字符串,判断字符串是否正确。
栈的基本应用,水题。自己比较得意的是如何判断是否匹配。方法是:
little = ‘(’ + ‘)’;
middle = ‘[’ + ‘]’;
判断当前字符和栈顶字符相加是否等于little 或middle
代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
const int little = '(' + ')';
const int middle = '[' + ']';
void judge(char c, char *parenthess, int *top)
{
if (c == ')' || c == ']')
{
if (c + parenthess[*top - 1] == little || c + parenthess[*top - 1] == middle)
{
--*top;
return;
}
}
parenthess[(*top)++] = c;
}
int main()
{
int n, top;
char parentheses[200];
char c;
while (~scanf("%d", &n))
{
getchar();
while (n--)
{
parentheses[0] = '#';
top = 1;
c = getchar();
while (c != '\n')
{
judge(c, parentheses, &top);
c = getchar();
}
if (top == 1)
{
printf("Yes\n");
}
else
{
printf("No\n");
}
}
}
return 0;
}