INPUT
3
PHPHP
2[3[P]H2[P]]
HH2[P3[H]]P
OUTPUT
PHPHP
PPPHPPPPPHPP
HHPHHHPHHHP
题意:扩展字符串。
思路:每次都先将括号匹配的位置记录下来,遍历一下还有没有括号,没有就结束,否则就继续遍历,每次循环去掉一个括号。
#include <algorithm>
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <cmath>
#include <queue>
#include <stack>
#include <cmath>
using namespace std;
#define MAX 1e9+7
#define inf 0x3f3f3f
const int M=1e5+10;
typedef long long ll;
stack<int> st;
using namespace std;
struct A{
char c;
int p;
} a[1010];
int main()
{
int n;
cin >> n;
while(n--)
{
string s;
cin >> s;
while(1)
{
memset(a, 0, sizeof(a));
while(!st.empty())
st.pop();
int len = s.size();
for (int i = 0; i < len; i++)
//记录括号匹配的位置,就是在左括号的位置赋上右括号的位置
{
a[i].c = s[i];
a[i].p = i;
if (s[i] == '[')
st.push(i);
if (s[i] == ']')
{
int topp = st.top();
a[topp].p = i;
st.pop();
}
}
int sum = 0;
for (int i = 0; i < len; i++)
if(s[i]=='[')
sum++;
if(sum==0)//结束条件
break;
string t;
//cout << "sum = :" << sum << endl;
int pp, pos1 = 0, pos2 = 0;
len = s.size();//每次长度都在变化
//cout << "len :" << len<<endl;
for (int i = 0; i < len; i++)
{
if (s[i] == '[')
{
pp = s[i - 1] - '0';//括号前面的系数
pos1 = i;
pos2 = a[i].p;
//每次去掉一个括号之后将字符串分为三部分,在分别连接起来
if (pos1 - 1 > 0)
t = s.substr(0, pos1 - 1);
else
t = "";
for (int j = 1; j <= pp; j++)
t += s.substr(pos1 + 1, pos2 - pos1 - 1);
if (len - pos2 > 0)
t += s.substr(pos2 + 1, len - pos2);
s = t;
break;//每次循环去掉一个系数
}
}
}
cout << s << endl;
}
return 0;
}