UVA 673 Parentheses Balance

来源:互联网 发布:软件认定企业查询 编辑:程序博客网 时间:2024/06/05 20:52


题意:给一个含'('、')'、'['、']'的括号序列,判断是否合法。


思路:用栈去判断一下。
1、如果遇到左括号就入栈。
2、如果遇到右括号
   1)栈空  不合法
   2)栈顶括号不与当前右括号匹配  不合法
   3)匹配  出栈,继续执行。

序列扫一遍之后,如果栈为空则序列合法,否则就有多余的括号。


#include <iostream>#include <cstdio>#include <stack>#include <cstring>using namespace std;int T;char temp[130];bool check(char temp[]){    stack<char> s;    int len = strlen(temp);    for(int i = 0; i < len; i++)        if ( temp[i] == '[' || temp[i] == '(' ) s.push(temp[i]);        else        {            if( s.empty() || ( s.top() == '(' && temp[i] == ']' ) || ( s.top() == '[' && temp[i] == ')' ) ) return false;            s.pop();        }    if ( s.empty() ) return true;    return false;}int main(){    cin>>T;    getchar();    while(T--)    {        gets(temp);        puts( check(temp)?"Yes":"No" );    }    return 0;}


0 0