关于计算式的栈的运用

2021秋招部分笔试题汇总 企业提供原题 00:25:49
3/6
[编程题]字符串算术运算
时间限制:C/C++ 1秒,其他语言2秒

空间限制:C/C++ 256M,其他语言512M

给定一个字符串式子,返回它的计算结果。算术规则为: k*[encoded_string],表示其中方括号内部的 encoded_string 正好重复 k 次。注意 k 保证为正整数。e.g. s = “3*[a2*[c]]”, 返回 “accaccacc”

输入例子1:
“3*[a2*[c]]”

输出例子1:
“accaccacc”

#include <iostream>
#include<bits/stdc++.h>
using namespace std;
const int maxn=1e6;
stack<char>st;


int main()
{
string s;
cin>>s;
string ans;
int len=s.length();
for(int i=0;i<s.length();i++)
{
    if(s[i]!=']')
    {
        st.push(s[i]);
    }
    else
    {
        string temp;
        while(!st.empty()&&st.top()>='a'&&st.top()<='z')
        {
           temp.insert(temp.begin(),st.top());
           st.pop();
        }
        st.pop();
        st.pop();
        temp=temp+ans;
        ans=temp;
        int cnt=0;
        int mi=0;
        while(!st.empty()&&st.top()>='0'&&st.top()<='9')
        {
            cnt+=(st.top()-48)*pow(10,mi++);
            st.pop();
        }
        for(int i=0;i<cnt-1;i++)
        {
            ans+=temp;
        }
    }
}
cout<<ans<<endl;
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值