A30883题解
2026-03-23 12:44:41
发布于:广东
7阅读
0回复
0点赞
题目分析
题目会给出一个序列(只有左右括号并且保证合法)
求从左到右匹配的括号的下标
举个栗子:
题目给的序列是:
( ( ) ) ( )
下标:0 1 2 3 4 5
那么从左到右第一个匹配的括号是1和2
第二个是0和3
第三个是4和5
那么我们的输出就是:
1 2
0 3
4 5
代码实现
我们需要栈的辅助
所以
#include<stack>
然后是初始化
char s; //记录每个下标的符号是什么
stack<int> st; //栈
int now=0; //当前下标
然后一直输入直到结束
while(cin>>s){
}
如果出现了右括号就表示有完整的括号出现了
if(s==')'){ //如果出现右括号
int ff=st.top(); //找到上一个左括号的下标
cout<<ff<<' '<<now<<endl;
st.pop(); //弹出上一个左括号
}
别忘了这一步
now++;
全代码
#include<iostream>
#include<stack>
using namespace std;
int main(){
char s;
stack<int> st;
int now=0;
while(cin>>s){
if(s==')'){
int ff=st.top();
cout<<ff<<' '<<now<<endl;
st.pop();
}else{
st.push(now);
}
now++;
}
return 0;
}
这里空空如也







有帮助,赞一个