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

#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; 
    }
}

猜你喜欢

转载自www.cnblogs.com/juanzhi/p/12726215.html