forked from tcandzq/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDecodeString.py
More file actions
39 lines (31 loc) · 1.35 KB
/
DecodeString.py
File metadata and controls
39 lines (31 loc) · 1.35 KB
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
35
36
37
38
39
"""
题号394 字符串解码
给定一个经过编码的字符串,返回它解码后的字符串。
编码规则为: k[encoded_string],表示其中方括号内部的 encoded_string 正好重复 k 次。注意 k 保证为正整数。
你可以认为输入字符串总是有效的;输入字符串中没有额外的空格,且输入的方括号总是符合格式要求的。
此外,你可以认为原始数据不包含数字,所有的数字只表示重复的次数 k ,例如不会出现像 3a 或 2[4] 的输入。
示例:
s = "3[a]2[bc]", 返回 "aaabcbc".
s = "3[a2[c]]", 返回 "accaccacc".
s = "2[abc]3[cd]ef", 返回 "abcabccdcdcdef".
参考:https://leetcode-cn.com/problems/decode-string/solution/decode-string-fu-zhu-zhan-fa-di-gui-fa-by-jyd/
"""
class Solution:
def decodeString(self, s: str) -> str:
stack,res,multi = [],"",0
for char in s:
if char == '[':
stack.append([multi,res])
res,multi = "", 0
elif char == ']':
cur_multi,last_res = stack.pop()
res = last_res + cur_multi * res
elif '0' <= char <= '9':
multi = multi * 10 + int(char)
else:
res += char
return res
if __name__ == '__main__':
s = "3[a]2[bc]"
solution = Solution()
print(solution.decodeString(s))