栈的应用(一)——括号的匹配

#include <cstring>
#include <cstdio>
#include <iostream>
#include <stack>

using namespace std;

int main(){
    string str;
    
    while(cin >> str){
        stack<int> bracks;
        int length = str.size();
        string answer(length,' ');
        
        for(int i = 0; i < length;i++){
            if(str[i] == '(' ){
                //!!! 
                bracks.push(i);
            }else if(str[i] == ')' ){
                if(!bracks.empty()){
                    bracks.pop();
                }else{
                    answer[i] = '?';
                }
            }
        }
        
        while(!bracks.empty()){
            answer[bracks.top()] = '$';
            bracks.pop();
        } 
        
        cout<<str<<endl; 
        cout<<answer<<endl; 
    }
}

 

posted @ 2020-04-18 15:40  天凉好个秋秋  阅读(142)  评论(0编辑  收藏  举报