2019华为初始笔试第二题

唉,当时脑子不清楚,第二题bug没解决,结束后又搞了十几分钟,发现substr参数错了,有个地方&&写成了||。。。

思路:这题可以用递归求,因为每个括号都可以递归,设函数func为求解函数, 那么func( abc(3(a)b)) ---> abc+3*func(a) + func(b)

因为每个str要么是数字开头,要么是字母开头,要么是括号开头, 只需要把数字提出来,然后递归括号里的就可以

代码:

#include <iostream>
#include <string>
#include <algorithm>
#include <cstring>
#include <stack>
using namespace std;

string fun(string str)
{
	if (str.size() == 0) return "";
	int i;
	stack<char>sta;
	string temp1, temp2, temp4;
	temp1 = "";
	temp2 = "";
	temp4 = "";//shuzi
	int int4;
	int pos;
	for (i = 0; i < str.size()&&(str[i]>='9'&&str[i]<='0'); ++i)
	{
		temp1 += str[i];
	}
	if (i >= str.size())
	{
		return temp1;
	}
	else
	{
		//shuzi
		if (str[i] <= '9'&&str[i] >= '0')
		{
			while (str[i] <= '9'&&str[i] >= '0')
			{
				temp4 += str[i];
				++i;
			}
			int4 = atoi(temp4.c_str());
			pos = i;
			sta.push(str[i]);
			++i;
			while (!sta.empty())
			{
				if (sta.top() == '(')
				{
					if (str[i] == ')')
					{
						sta.pop();
					}
					else
					{
						if (str[i] == '(' || str[i] == '[' || str[i] == '{')
							sta.push(str[i]);
					}
				}
				else if (sta.top() == '[')
				{
					if (str[i] == ']')
					{
						sta.pop();
					}
					else
					{
						if (str[i] == '(' || str[i] == '[' || str[i] == '{')
							sta.push(str[i]);
					}
				}
				else if (sta.top() == '{')
				{
					if (str[i] == '}')
					{
						sta.pop();
					}
					else
					{
						if (str[i] == '(' || str[i] == '[' || str[i] == '{')
							sta.push(str[i]);
					}
				}
				++i;
			}
			temp2 = fun(str.substr(pos + 1, i - 2 - pos));
			for (int j = 0; j < int4; ++j)
			{
				temp1 += temp2;
			}
			if (i >= str.size())
			{
				return temp1;
			}
			else
			{
				return temp1 + fun(str.substr(i, str.size() - i));
			}
		}
		else
		{
			pos = i;
			sta.push(str[i]);
			++i;
		
			while (!sta.empty())
			{
				if (sta.top() == '(')
				{
					if (str[i] == ')')
					{
						sta.pop();
					}
					else
					{
						if (str[i] == '(' || str[i] == '[' || str[i] == '{')
							sta.push(str[i]);
					}
				}
				else if (sta.top() == '[')
				{
					if (str[i] == ']')
					{
						sta.pop();
					}
					else
					{
						if (str[i] == '(' || str[i] == '[' || str[i] == '{')
							sta.push(str[i]);
					}
				}
				else if (sta.top() == '{')
				{
					if (str[i] == '}')
					{
						sta.pop();
					}
					else
					{
						if (str[i] == '(' || str[i] == '[' || str[i] == '{')
							sta.push(str[i]);
					}
				}
				++i;
			}
			temp2 = fun(str.substr(pos + 1, i - 2 - pos));
			temp1 += temp2;
			if (i >= str.size())
			{
				return temp1;
			}
			else
			{
				return temp1 + fun(str.substr(i, str.size() - i));
			}
		}
	}
}
int main()
{
	string str;
	cin >> str;
	cout << fun(str);
}

实例:     

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值