HDU 1274(展开字符串)

使用栈存储输入的字符,每次读取一个字符,分情况操作:

  1. 字符为数字和左括号,直接入栈;
  2. 字符为小写字母,如果栈顶元素不是数字,直接入栈;如果栈顶元素是数字,将当前字母展开后入栈;
  3. 字符为右括号,将字符依次出栈并存入临时数组,直到栈顶元素为左括号,将左括号出栈并舍弃。如果左括号前有数字,则将其出栈;如果左括号前没有数字或者栈为空,则默认数字为1。将括号中的所有字符展开后再次入栈;
  4. 字符为换行符,将栈中所有字符出栈,反向输出。
#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;
}

继续加油。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值