使用栈存储输入的字符,每次读取一个字符,分情况操作:
- 字符为数字和左括号,直接入栈;
- 字符为小写字母,如果栈顶元素不是数字,直接入栈;如果栈顶元素是数字,将当前字母展开后入栈;
- 字符为右括号,将字符依次出栈并存入临时数组,直到栈顶元素为左括号,将左括号出栈并舍弃。如果左括号前有数字,则将其出栈;如果左括号前没有数字或者栈为空,则默认数字为1。将括号中的所有字符展开后再次入栈;
- 字符为换行符,将栈中所有字符出栈,反向输出。
#include <iostream>
#include <stack>
#include <cctype>
#include <cstring>
using namespace std;
stack<char> st;
char temp[250000]; //展开时括号中的字符
int main()
{
int N;
cin >> N;
char c;
cin.get(); //读入N之后的换行符
while (cin.get(c))
{
if (isdigit(c) || c == '(') //数字和左括号直接入栈
st.push(c);
else if (islower(c)) //字母
{
if (!isdigit(st.top())) //栈顶元素不是数字,直接入栈
st.push(c);
else //栈顶元素是数字,将当前字母展开后入栈
{
int num = st.top() - '0'; //字母前的数字
st.pop();
for (int i = 0; i < num; i++) //展开
st.push(c);
}
}
else if (c == ')') //右括号
{
int index = 0; //括号中字母的数量
while (st.top() != '(') //将括号中的字母存入数组
{
temp[index++] = st.top();
st.pop();
}
st.pop(); //舍弃左括号
int num; //括号前的数字
if (st.empty() || !isdigit(st.top())) //括号前没有数字,默认为1
num = 1;
else //括号前有数字
{
num = st.top() - '0';
st.pop();
}
--index;
for (int i = 0; i < num; i++) //将括号中的字母展开后入栈
{
for (int j = index; j >= 0; j--)
st.push(temp[j]);
}
}
else if (c == '\n') //换行符
{
int index = 0;
while (!st.empty())
{
temp[index++] = st.top();
st.pop();
}
for (int i = --index; i >= 0; i--)
cout << temp[i];
cout << endl;
if (--N == 0)
break;
}
}
return 0;
}
继续加油。