Parentheses Balance(栈)

来源:互联网 发布:bt离线下载软件 编辑:程序博客网 时间:2024/05/29 17:14

Question:题目详情(http://vjudge.net/contest/134361#problem/D)
题目大意:只有()[] 四种字符,空串为平衡,()[]都为平衡,平衡里面嵌套平衡也是平衡的
解题思路:用一个栈遇到’ [ ‘,’(‘时就推入遇到’ )” ] ‘时就与栈顶匹配,如果能匹配就婆婆,最终判断栈是否为空,如为空则平衡,否则不平衡。但注意:))))]]]这种情况用上述方法判断是平衡的,所以这一类的就要单独判断

#include <iostream>#include <cstdio>#include <cstring>#include <stack>using namespace std;int main(){    stack<char> s;    int n;    cin>>n;    getchar();    while(n--)    {        int flag=1;        while(!s.empty())  //清除上次的残留            s.pop();        char ch;        while((ch=getchar())!='\n')  //此循环结束读入了一行        {            if(ch=='('||ch=='[')  //遇到'('']'就push                s.push(ch);            if(ch==')'||ch==']')            {                if(s.empty())  //如果匹配时栈顶为空,说明绝对是不匹配的                    flag=0;                else if((s.top()=='('&&ch==')')||(s.top()=='['&&ch==']'))  //匹配成功                    s.pop();            }        }        if(flag==1&&s.empty())            cout<<"Yes"<<endl;        else cout<<"No"<<endl;    }}

体会:以前也遇到类似的问题,所以这道题很快就想到解法了

0 0
原创粉丝点击