zoukankan      html  css  js  c++  java
  • 栈(括号匹配)

    假设一个算术表达式中可以包含三种括号:圆括号“(”和“)”,方括号“[”和“]”和花括号“{”和“ ”,且这三种括号可按任意的次序嵌套使用(如:…[…{… …[…]…]…[…]…(…)…)。编写判别给定表达式中所含括号是否正确配对出现的算法。输出结果YES 或者 NO。

    Input

    5+{[2X5]+2}

    Output

    YES

    Sample Input

    8-[{2+7]}

    Sample Output

    NO

    #include<iostream>
    #include<stack>
    #include<cstring>
    #include<cstdio>
    using namespace std;
    int main()
    {
        stack<char> s;
        char a[10000]={0},t;
        int l;
        gets(a);
        l=strlen(a);
        for(int i=0;i<=l-1;++i)
        {
            if(a[i]=='('||a[i]=='['||a[i]=='}')
            {
                s.push(a[i]);
            }
            if(a[i]==')')
            {
               t=s.top();
               if(t=='(')
                   s.pop();
               else
               {
                   cout<<"NO"<<endl;
                   return 0;
               }
            }
            if(a[i]==']')
            {
               t=s.top();
               if(t=='[')
                   s.pop();
               else
               {
                   cout<<"NO"<<endl;
                   return 0;
               }
            }
            if(a[i]=='}')
            {
               t=s.top();
               if(t=='{')
                   s.pop();
               else
               {
                   cout<<"NO"<<endl;
                   return 0;
               }
            }
        }
            cout<<"YES"<<endl;
        return 0;
    }
  • 相关阅读:
    Less-21
    Less-22
    Less-21
    Less-20
    ssrf redis gopher
    Less19
    Less18
    Arm 系统查看、修改系统时间
    通过 grpc 请求标头发送自定义数据
    gRpc 空参数
  • 原文地址:https://www.cnblogs.com/ljhacm/p/6722447.html
Copyright © 2011-2022 走看看