Given a string containing just the characters ‘(‘, ‘)’, ‘{‘, ‘}’, ‘[’ and ‘]’, determine if the input string is valid.
The brackets must close in the correct order, “()” and “()[]{}” are all valid but “(]” and “([)]” are not.
#include <stdio.h>
#include <string.h>
//数据结构:栈
//算法:抓取到左括号,就将它推入栈(push);抓取到右括号,就pop,取出一个左括号,判断是否匹配,如果匹配则继续;不匹配立即结束循环,输出false。
int stack[1000];
int len_stack;
int pop(void)
{
//自己想
}
void push(int new_element)
{
//自己想
}
int trans(char c)//把括号转化为数字来处理
{
switch (c)
{
case '{':return 1;
case '}':return 2;
case '[':return 3;
case ']':return 4;
case '(':return 5;
case ')':return 6;
}
}
int main()
{
char exp[10000];
scanf("%s",&exp);
long len_exp =strlen(exp);
int boo=1;//boo为1代表匹配,为0代表不匹配
int t,i;
len_stack=0;
for (i=0;i<len_exp;i++)
{
t=trans(exp[i]);
if (t%2==0)
{
if (len_stack==0) //如果栈中没了元素,说明右括号前面没有左括号,
{
boo=0;
break;
}
else
{
if (pop()+1!=t)
{
boo=0;
break;
}
}
}
else push(t);
}
if (len_stack!=0) boo=0;
if (boo==0) printf("False\n");
else printf("True\n");
}