栈的运用

展开括号中字符串

就是有数字有字母,括号,要求按括号展开字符串,并且匹配相应模式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
/*
2(A2(AN)) 可以转成 AANAN AANAN
利用栈的知识 设置一个数字栈和字符串栈
每次没遇到左右括号 就拼接数字或者字符串
如果遇到左括号,就入栈数字和字符串
如果遇到右括号,就出栈数字和字符串进行组合,并且加到目前字符串栈顶后面
*/
string parse(const string& s) {
stack<int> numStk;
stack<string> strStk;
string res;
int num = 0;
for (char c : s) {
if (isdigit(c)) {
num = num * 10 + (c - '0');
} else if (c == '(') {
numStk.push(num);
num = 0;
strStk.push(res);
res = "";
} else if (c == ')') {
string temp = res;
for (int i = 0; i < numStk.top() - 1; ++i) {
res += temp;
}
res = strStk.top() + res;
strStk.pop();
numStk.pop();
} else {
res += c;
}
}
return res;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# py版本感觉更简洁 多学学
def parse(s):
num_stack = []
str_stack = []
res = ""
num = 0
for c in s:
if c.isdigit():
num = num * 10 + int(c)
elif c == '(':
num_stack.append(num)
num = 0
str_stack.append(res)
res = ""
elif c == ')':
temp = res
for _ in range(num_stack.pop() - 1):
res += temp
res = str_stack.pop() + res
else:
res += c
return res

栈的运用
https://rain_dew.gitee.io/2024/05/16/专业课/数据结构/3.栈,队列,数组/栈的应用/
Author
Wang yulu
Posted on
May 16, 2024
Licensed under