唉,当时脑子不清楚,第二题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);
}
实例: