计蒜客 括号匹配(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;
}

优质内容筛选与推荐>>
1、centos 6.5 X64 安装 mongodb 2.6.1 (笔记 实测)
2、【selenium】常见问题
3、Android 小随笔2
4、关于iPhone X 适配
5、装饰器习题一些基本的


长按二维码向我转账

受苹果公司新规定影响,微信 iOS 版的赞赏功能被关闭,可通过二维码转账支持公众号。

    阅读
    好看
    已推荐到看一看
    你的朋友可以在“发现”-“看一看”看到你认为好看的文章。
    已取消,“好看”想法已同步删除
    已推荐到看一看 和朋友分享想法
    最多200字,当前共 发送

    已发送

    朋友将在看一看看到

    确定
    分享你的想法...
    取消

    分享想法到看一看

    确定
    最多200字,当前共

    发送中

    网络异常,请稍后重试

    微信扫一扫
    关注该公众号