56分求助

P1241 括号序列

fenboQAQ @ 2023-07-07 11:41:30

#include <bits/stdc++.h>
using namespace std;
char a[10005],b[10005],len1 = 0,len2 = 0;
bool dis[100005];
int main(){
    string s;
    cin >> s;
    for(int i = 0;i < s.size();i ++){
        if(s[i] == '[' || s[i] == '('){
            dis[i] = false;
        }
        else{
            for(int j = i - 1;j >= 0;j --){
                if(s[i] == ')') if(s[j] == '(') dis[i] = true,dis[j] = true;
                if(s[i] == ']') if(s[j] == '[') dis[i] = true,dis[j] = true;
                if(s[i] == ')'){
                    if(s[j] == '[' || s[j] == ']') break;
                }
                if(s[i] == ']'){
                    if(s[j] == '(' || s[j] == ')') break;
                }
            }
        }
    }
    for(int i = 0;i < s.size();i ++){
        if(dis[i] == false){
            if(s[i] == '(') cout << s[i] << ')';
            if(s[i] == ')') cout << '(' << s[i];
            if(s[i] == '[') cout << s[i] << ']';
            if(s[i] == ']') cout << '[' << s[i];
        }
        else{
            cout << s[i];
        }
    }
    return 0;
}

by __Deng_Rui_Song__ @ 2023-12-19 17:37:29

@fenboQAQ 题目意思是出现了右括号,找到最近的未匹配左括号;你并没有判断是否匹配\ 把

if(s[i] == ')') if(s[j] == '(') dis[i] = true,dis[j] = true;
if(s[i] == ']') if(s[j] == '[') dis[i] = true,dis[j] = true;
if(s[i] == ')'){
    if(s[j] == '[' || s[j] == ']') break;
}
if(s[i] == ']'){
    if(s[j] == '(' || s[j] == ')') break;
}

改成

if(s[i] == ')'){
    if((s[j] == '('||s[j] == '[') &&  dis[j] == false){
        if(s[j] == '(') dis[i] = true,dis[j] = true;
        break;
    }
}
if(s[i] == ']'){
    if((s[j] == '('||s[j] == '[') &&  dis[j] == false){
        if(s[j] == '[') dis[i] = true,dis[j] = true;
        break;
    }
}

把你的上下两个if合并了


|