Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit f892af4

Browse files
🐱(stack): 394. 字符串解码
Python 栈版本优化
1 parent 5ab82ad commit f892af4

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed

‎docs/data-structure/stack/README.md‎

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -991,6 +991,38 @@ class Solution:
991991
return ''.join(stack)
992992
```
993993

994+
优化:
995+
996+
1. 将数字记录在 `multi` 中,字母记录在 `res`
997+
2. 遇到 `[` 时,将 `[multi, res]` 入栈,并重置 `multi``res`
998+
3. 遇到 `]` 时,从栈顶取元素 `[num, string]`,并计算 `res = string + num * res`
999+
1000+
```python
1001+
class Solution:
1002+
def decodeString(self, s: str) -> str:
1003+
stack = []
1004+
# 存放字符串和数字
1005+
res, multi = '', 0
1006+
# ans = ''
1007+
for c in s:
1008+
if c == '[':
1009+
# 已经统计的 res 和 multi 入栈
1010+
stack.append([res, multi])
1011+
res, multi = '', 0
1012+
elif c == ']':
1013+
# 出栈并计算结果
1014+
string, num = stack.pop()
1015+
res = string + res * num
1016+
elif '0' <= c and c <= '9':
1017+
# 记录数字
1018+
multi = 10 * multi + int(c)
1019+
else:
1020+
# 遇到字母
1021+
res += c
1022+
# print(stack)
1023+
return res
1024+
```
1025+
9941026
## 503. 下一个更大元素 II
9951027

9961028
[原题链接](https://leetcode-cn.com/problems/next-greater-element-ii/submissions/)

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /