九度26 括号匹配问题

//从左向右将(压入栈,遇到)则将栈顶匹配给它,由于栈的特性相当于从内向外匹配

#include <iostream>
#include <algorithm>
#include<string>
#include<stack>

using namespace std;
stack<int> s;
char str[101];
char res[101];

void main()
{
    while (cin >> str)
    {
        int i,len=strlen(str);
        for (i = 0; i < len; i++)
        {
            if (str[i] == '(')
                s.push(i);
            else if (str[i] == ')')
            {
                if (!s.empty())
                {
                    int tmp = s.top();
                    res[tmp] = ' ';
                    s.pop();
                    res[i] = ' ';
                }
                else
                {
                    res[i] = '?';
                }
                
            }
            else res[i] = ' ';
            
        }
        if (!s.empty())
        {
            while (!s.empty())
            {
                int tmp;
                tmp=s.top();
                res[tmp] = '$';
                s.pop();
            }
        }
        for (i = 0; i < len; i++)
            cout << str[i];
        cout << endl;
        for (i = 0; i < len; i++)
            cout << res[i];
        cout << endl;
    }
        
    
}

猜你喜欢

转载自blog.csdn.net/KingsCC/article/details/81672122