zoukankan      html  css  js  c++  java
  • 计蒜客 括号匹配(stack+map)

    题意

    蒜头君在纸上写了一个串,只包含’(‘和’)’。一个’(‘能唯一匹配一个’)’,但是一个匹配的’(‘必须出现在’)’之前。请判断蒜头君写的字符串能否括号完全匹配,如果能,输出配对的括号的位置(匹配的括号不可以交叉,只能嵌套)。
    输入格式
    一行输入一个字符串只含有’(‘和’)’,输入的字符串长度不大于50000。
    输出格式
    如果输入括号不能匹配,输出一行”No”,否则输出一行”Yes”,接下里若干行每行输出 2 个整数,用空格隔开,表示所有匹配对的括号的位置(下标从 1 开始)。你可以按照任意顺序输出。
    本题答案不唯一,符合要求的答案均正确
    样例输入
    ()()
    样例输出
    Yes
    1 2
    3 4

    #include <iostream>
    #include <cstring>
    #include <cstdio>
    #include <algorithm>
    #include <queue>
    #include <stack>
    #include <string>
    #include <map>
    
    using namespace std;
    
    string Ch;
    stack<int>S;
    map<int,int>mp;
    int flag=1;
    
    int main()
    {
        ios::sync_with_stdio(false);cin.tie(0);
        cin>>Ch;
        for(int i=0;i<Ch.length();i++){
            if(Ch[i]=='(')
            {
                S.push(i);
            }
            else if(Ch[i]==')')
            {
                if(!S.empty())
                {
                     mp[S.top()]=i;
                        S.pop();
                }
                else
                {
                    flag=0;
                    break;
                }
            }
        }
    
        if(flag&&S.empty()) {
            cout<<"Yes"<<endl;
            for(map<int,int>::iterator it=mp.begin();it!=mp.end();it++){
                cout<<(it->first)+1<<" "<<(it->second)+1<<endl;
            }
        }
        else cout<<"No"<<endl;
    
        return 0;
    }
  • 相关阅读:
    Mobile phones(poj1195)
    Matrix(poj2155)
    1080
    1266
    codeforces626D . Jerry's Protest
    字符串格式化
    附加MySQL数据库的方法
    avaScript中变量的声明和赋值
    选择法排序
    JavaScript中变量的类型
  • 原文地址:https://www.cnblogs.com/Fy1999/p/9396988.html
Copyright © 2011-2022 走看看