56pt

P1241 括号序列

Foggy_night @ 2023-04-28 12:42:42

#include<iostream>
#include<cstring>
using namespace std;
string s;
int w[105];
char a[105], ch[105];
int main(){
    cin >> s;
    int len = s.size();
    int j = 0;
    for(int i = 0; i < len; i++){
        if(s[i] == '('){
            a[j++] = s[i];
            w[j] = i;
            ch[i] = ')';
        }
        if(s[i] == '['){
            a[j++] = s[i];
            w[j] = i;
            ch[i] = ']';
        }
        if(s[i] == ')')
        {
            if(j && a[j] == '(')
                ch[w[j--]]=' ';
            else ch[i]='(';
        } 
        if(s[i] == ']')
        {
            if(j && a[j] == '[')
                ch[w[j--]]=' '; 
            else ch[i]='[';
        }
    }
    for(int i = 0; i < len; i++){
        if(ch[i] == '(' || ch[i] == '[') cout << ch[i] << s[i];
        else if(ch[i] == ')' || ch[i] == ']') cout << s[i] << ch[i];
        else cout << s[i];
    }
    return 0;
}

|