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;
}