P1241 括号序列 68分求助

P1241 括号序列

``` #include <cstdio> #include <iostream> #include <cstring> #include <string> using namespace std; int t,w[110]; string a; char s[110],c[110]; int main() { cin >> a; int n=a.length(); for(int i=0;i<n;i++) { if(a[i] == '(' || a[i] == '[') { s[++t]=a[i]; w[t]=i; if(a[i] == '(') c[i]=')'; else c[i]=']'; } if(a[i] == ')') { if(t&&s[t]=='(') { c[w[t]]=' '; t--; } else c[i]='('; } if(a[i] == ']') { if(t&&s[t]=='[') { c[w[t]]=' '; t--; } 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]); } return 0; }#include <cstdio> #include <iostream> #include <cstring> #include <string> using namespace std; int t,w[110]; string a; char s[110],c[110]; int main() { cin >> a; int n=a.length(); for(int i=0;i<n;i++) { if(a[i] == '(' || a[i] == '[') { s[++t]=a[i]; w[t]=i; if(a[i] == '(') c[i]=')'; else c[i]=']'; } if(a[i] == ')') { if(t&&s[t]=='(') { c[w[t]]=' '; t--; } else c[i]='('; } if(a[i] == ']') { if(t&&s[t]=='[') { c[w[t]]=' '; t--; } 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]); } return 0; } ```
by wrk20111205 @ 2023-10-01 15:23:09


求关注,谢谢
by wrk20111205 @ 2023-10-01 15:23:43


我来提供一个AC的代码 ``` #include<iostream> #include<stack> #include<queue> using namespace std; const int MAXS = 1e3+10; int n; string str; stack<char> st; queue<char> q; int pos[MAXS]; int main(){ cin >> str; int cnt = 0,tp = 0; for(int i = 0;i < str.size();i++){ if(str[i] == '(' || str[i]== '['){ st.push(str[i]); pos[++cnt] = 1; tp = cnt; }else{ bool flag = false; if(st.empty()) flag = true; else if( (st.top() == '(' && str[i] == ']') || (st.top() == '[' && str[i] == ')') ) flag = true; else if( (st.top() == '(' && str[i] == ')') || (st.top() == '[' && str[i] == ']') ){ st.pop(); while(pos[tp] == 0)tp--; pos[tp] = 0; } if(flag){ if(str[i] == ')')pos[++cnt] = 0,q.push('('); if(str[i] == ']')pos[++cnt] = 0,q.push('['); } } q.push(str[i]); } int id = 0; while(!q.empty()){ cout << q.front(); int f = q.front(); if(f == '('){ id++; if(pos[id] == 1)cout << ')'; } else if(f == '['){ id++; if(pos[id] == 1)cout << ']'; } q.pop(); } return 0; } ```
by HuY2397061185 @ 2023-10-21 16:38:50


|