判断字符串中左右括号是否匹配
题目描述:给定一个只包括 ‘(’,’)’,’{’,’}’,’[’,’]’ 的字符串 s ,判断字符串是否有效。
有效字符串需满足:
1、左括号必须用相同类型的右括号闭合。
2、左括号必须以正确的顺序闭合。
题目来源:力扣(LeetCode)
bool isValid(char * s){
Stack st;
StackInit(&st);
while(*s)
{
//左括号入栈
//右括号找最近的左括号匹配
if(*s == '[' || *s == '(' || *s == '{')
{
StackPush(&st,*s);
s++;
}
else
{
//为空,说明没有前括号
if(StackEmpty(&st))
{
StackDestory(&st);
return false;
}
char top = StackTop(&st);
if((top == '[' && s != ']')
||(top == '(' && s != ')')
||(top == '{' && s != '}'))
{
StackDestory(&st);
return false;
}
else
{
//匹配
StackPop(&st);
s++;
}
}
}
bool ret = StackEmpty(&st);
StackDestory(&st);
return ret;
}
注:代码中的函数在我的另一篇文章中实现栈