提示
把字符串展开
例如:
Example1:
1(1a2b1(ab)1c)
abbabc
Example2:
3(ab2(4ab))
abaaaabaaaababaaaabaaaababaaaabaaaab
代码
#include <iostream>
#include <stack>
using namespace std;
//栈顶是数字,并且要入栈字符是字母
bool num_let(char top, char str = 'k') {
return (top <= '9' && top >= '0') && (str <= 'z' && str >= 'A');
}
//递归打印栈内容
void show(stack<char> &S) {
while (!S.empty()) {
char temp = S.top();
S.pop();
show(S);
cout << temp;
}
}
int main() {
//1(1a2b1(ab)1c)
string str = "3(ab2(4ab))";
stack<char> S;
for (int i = 0; str[i] != '\0'; ++i) {
if (S.empty()) {
S.push(str[i]);
} else {
if (num_let(S.top(), str[i])) {
int temp = S.top() - '0';
S.pop();
while (temp--) {
S.push(str[i]);
}
} else if (str[i] == ')') {
string tem;
char c;
while (!S.empty()) {
c = S.top();
S.pop();
if (!num_let(c) && c != '(') {
tem = c + tem;
} else {
if (c != '(') {
int n = c - '0';
while (n--) {
for (int k = 0; tem[k] != '\0'; ++k) {
S.push(tem[k]);
}
}
break;
}
}
}
} else {
S.push(str[i]);
}
}
}
show(S);
return 0;
}