王道机试指南 例题5.5 括号匹配问题

题目:

代码:

#include <iostream>
#include <stack>
using namespace std;

int main(){
    string str;
    while(getline(cin,str)){
        stack<char> s1;//存放待匹配的左括号
        stack<int> s2;//存放待匹配左括号的下标
        char ans[str.size()];//存放结果字符的数组

        for(int i=0;i<str.size();i++)//初始化结果数组为全空格
            ans[i]=' ';
        for(int i=0;i<str.size();i++){//开始匹配
            if(str[i]=='('){//如果遇到左括号则入栈
                s1.push(str[i]);
                s2.push(i);
            }
            else if(str[i]==')'){//如果遇到右括号
                if(s1.empty()==0){//栈不空则匹配成功
                    s1.pop();
                    s2.pop();
                }
                else//栈空则匹配失败
                    ans[i]='?';
            }
        }
        while(s1.empty()==0){//栈中剩下的左括号匹配失败
            ans[s2.top()]='$';
            s1.pop();
            s2.pop();
        }
        cout<<str<<endl;
        cout<<ans<<endl;

        for(int i=0;i<str.size();i++)
            ans[i]=' ';
    }
    return 0;
}

运行结果:

全部评论

相关推荐

深夜书店vv:腾讯是这样的,去年很多走廊都加桌子当工区
点赞 评论 收藏
分享
点赞 评论 收藏
分享
评论
点赞
7
分享

创作者周榜

更多
牛客网
牛客企业服务