怎么卡48了求帮助

P1241 括号序列

PrincedeChine @ 2024-10-02 10:19:55

#include<iostream>
#include<cstring>

using namespace std;

void Complete(const string &s){
    int a;
    int i;
    a = s.length();
    for(i = a - 1; i >= 0; i--){
        if(s[i] == ')'){
            if(i > 0 && s[i-1] == '('){
                cout << "()";
                i--;
            }
            else{
                cout << "()";
            }
        }
        if(s[i] == ']'){
            if(i > 0 && s[i-1] == '['){
                cout << "[]" ;
                i--;
            }
            else{
                cout << "[]" ;
            }
        }
        if(s[i]=='('){
            cout<<"()";
        }
        if(s[i]=='['){
            cout<<"[]";
        }
    }

}

int main(){
    string s;
    cin >> s;
    Complete(s);
    return 0;
}

by 伊可怀也 @ 2024-10-09 17:55:25

我也卡48了 蹲蹲


by HerobrinePerssonZ @ 2024-10-13 17:01:50

@PrincedeChine @伊可怀也

代码带解析

#include <cstdio>
#include <iostream>
#include <cstring>
#include <string>

using namespace std;
int top,w[110];
string a;
char s[110],c[110];
int main()
{
//  freopen("work.in","r",stdin);freopen("work.out","w",stdout);
    cin >> a;
    int n=a.length();
    for(int i=0;i<n;i++)
    {
        if(a[i] == '(' || a[i] == '[')
        {
            s[++top]=a[i];
            w[top]=i;
            if(a[i] == '(') c[i]=')';
            else c[i]=']';
        }
        if(a[i] == ')')
        {
            if(top && s[top] == '(') {c[w[top]]=' '; top--;}
            else c[i]='(';
        } 
        if(a[i] == ']')
        {
            if(top && s[top] == '[') {c[w[top]]=' '; top--;}
            else c[i]='[';
        }
    }
    for(int i=0;i<n;i++)
    {
        if(c[i] == '(' || c[i] == '[') printf("%c%c",c[i],a[i]);
        else if(c[i] == ')' || c[i] == ']') printf("%c%c",a[i],c[i]);
        else printf("%c",a[i]);
    }
//  fclose(stdin);fclose(stdout);
    return 0;
}

加团or关注


|