猿辅导笔试编程题二

1.叠箱子问题——倒序+栈,不知道对不对。

#include <stack>
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int main(){
    string s;
    cin>>s;
    reverse(s.begin(),s.end());
    stack<int> stk;
    int i=0,n=s.size();
    stack<int> stack;
    while(i<n){
        char c=s[i];
        if(s[i]==']'){  //倒序,故而】为左边界
            if(stk.empty()||s[i-1]=='['||s[i-1]==']'){  //保证单个纸箱子左侧也有计数值1.
                stk.push(1);
            }
            stk.push(0);
        }
        else if(c=='['){    //遇到右边界
            if(stk.top()==0){   //如果是没有套小箱子,则直接出左边界0。
                stk.pop();
            }
            else{               //如果套了小箱子,则统计内部箱子数目,取k=1保证后续将自身计算进去。
                int k=1;
                while(!stk.empty()&&stk.top()!=0){
                    k+=stk.top();
                    stk.pop();
                }
                stk.pop();
                stk.top()*=k;
            }
        }
        else{
            stk.push(c-'0');
        }
        ++i;
    }
    int res=0;
    while(!stk.empty()){
        res+=stk.top();
        stk.pop();
    }
    cout<<res<<endl;
    return 0;
}
#猿辅导##笔试题目#
全部评论
正序➕栈也可以呀,已经出来了
点赞 回复
分享
发布于 2021-08-01 13:21

相关推荐

头像
B站 运营岗 普通Offer是12-15k*15-18,SP的Offer月薪16-17k*15,SSP的offer月薪是20k*15,综合年总包区间在18-30W。
点赞 评论 收藏
转发
点赞 1 评论
分享
牛客网
牛客企业服务