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

實例:     

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章