• 括号配对问题 栈(stack)的利用


    题目来源:http://acm.nyist.net/JudgeOnline/problem.php?pid=2

    括号配对问题

    时间限制:3000 ms  |  内存限制:65535 KB
    难度:3
     
    描述
    现在,有一行括号序列,请你检查这行括号是否配对。
     
    输入
    第一行输入一个数N(0<N<=100),表示有N组测试数据。后面的N行输入多组输入数据,每组输入数据都是一个字符串S(S的长度小于10000,且S不是空串),测试数据组数少于5组。数据保证S中只含有"[","]","(",")"四种字符
    输出
    每组输入数据的输出占一行,如果该字符串中所含的括号是配对的,则输出Yes,如果不配对则输出No
    样例输入
    3
    [(])
    (])
    ([[]()])
    样例输出
    No
    No
    Yes
    分析:
    当栈非空时,插入的字符如果等于栈顶元素,则弹出栈顶元素,否则插入字符。 当栈为空时, 直接插入字符。当所有的字符处理完后,栈为空,则所有括号是配对的,否则,不配对。
    代码如下:
    #include <cstdlib>
    #include <cstring>
    #include <algorithm>
    #include <cstdio>
    #include <cmath>
    #include <iostream>
    #include <vector>
    #include<string>
    #include<cstring>
    #include<string.h>
    #include<set>
    #include<queue>
    #include<stack>
    #include<map>
    using namespace std;
    typedef long long LL;
    char s[10010];
    int main()
    {
        int t;
        cin>>t;
        while(t--)
        {
            stack<char>st;
            char c;
            cin>>s;
            int len=strlen(s);
            st.push(s[0]);
            for(int i=1;i<len;i++)
            {
                if(st.empty())   // 因为缺少这个判断,一直re,栈为空时要注意
                {
                    st.push(s[i]);
                    continue;
                }
                c=st.top();
                if((c=='[' && s[i]==']' )|| (c=='(' && s[i]==')'))
                    st.pop();
                else st.push(s[i]);
            }
            if(st.empty()) puts("Yes");
            else puts("No");
            }
        return 0;
    }


  • 相关阅读:
    共享内存:mmap函数实现
    navigationItem.rightBarButtonItem 设置背景图片,颜色更改解决的方法
    C语言基础
    easyui datagrid合并相同数据的单元格。
    js 计算总页数的最高效方式
    取消本地文件夹与SVN服务器的关联
    扩展自easyui的combo组件的下拉多选控件
    利用art.template模仿VUE 一次渲染多个模版
    利用art.template模仿VUE
    JavaScript单独的模块中传递数据
  • 原文地址:https://www.cnblogs.com/zn505119020/p/3621732.html
Copyright © 2020-2023  润新知