4 条题解
-
2
这道题匹配的方式是真的没有讲清楚
看了几遍题目一脸懵
~甚至看了题解也还是一脸懵~
那这里我还是想把题意讲的更简单理解一点
原题目:扫描一遍原序列,对每一个右括号,找到在它左边最靠近它的左括号匹配,如果没有就放弃。
翻译:扫描一遍原序列,当找到一个右括号(即找到一个 ' ) ' 或者 ' ] ' 时),以它为起点向左找,找到一个没被标记成功匹配的左括号(即找到一个 ' ( ' 或者 ' [ ' ),如果两者匹配的话,标记它们成功 ~牵手~ 匹配,如果不匹配,或者找不到左括号的话,不做任何标记。
原题目:在以这种方式把原序列匹配完成后,把剩下的未匹配的括号补全。
翻译:上面扫描一遍标记完成功匹配的括号之后,扫描一遍序列,对于标记过的括号,则直接输出;对于没有标记的括号,则补全成对输出
举例:如果有个 ' [ ' 或 ' ] ' 没被标记匹配,则输出 [ ]
如果还不理解的话,给个测试样例:
输入:( [ ) ] )
输出:( [ ( ) ] )
#include<bits/stdc++.h> using namespace std; int top,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[++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]); } return 0; }
-
2
题解:
#include<bits/stdc++.h> using namespace std; int top,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[++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]); } return 0; }
- [ ] 任务完成 😄
-
1
#include<iostream> #include<stack> using namespace std; struct KH{ int i; char c; }; bool flag[105]; int main(){ string str; cin>>str; KH t; stack<KH>s; for(unsigned int i=0;i<str.size();++i){ t.i=i; t.c=str[i]; if(str[i]=='('||str[i]=='[')s.push(t); else if(!s.empty()){ if(str[i]==')'&&s.top().c=='('||str[i]==']'&&s.top().c=='['){ flag[i]=flag[s.top().i]=true; s.pop(); } } } for(unsigned int i=0;i<str.size();++i){ if(flag[i]==false){ if(str[i]=='('||str[i]==')')cout<<"()"; else cout<<"[]"; }else cout<<str[i]; } return 0; }
- 1
信息
- ID
- 242
- 时间
- 1000ms
- 内存
- 128MiB
- 难度
- 2
- 标签
- 递交数
- 16
- 已通过
- 9
- 上传者