-
题目链接 https://leetcode-cn.com/problems/decode-string/comments/
-
题目描述
-
给定一个经过编码的字符串,返回它解码后的字符串。
编码规则为:
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".
-
-
解题思路
- 栈模拟。遍历字符串,假设当前字符为s,s为字母或是'['则入栈。为数字,需要将整个数集齐再入栈。若为']'出栈累加字符直到遇到’]‘,出栈数字与累加的字符相乘再入栈
-
代码
- python
class Solution: def decodeString(self, s: str) -> str: st = [] for i in s: if i == ']': tmp = st.pop() while st[-1] != '[': tmp = st.pop() + tmp st.pop() st.append(int(st.pop()) * tmp) elif i.isdigit(): st.append(str(int(st.pop()) * 10 + int(i)) if st and st[-1].isdigit() else i) else: st.append(i) return ''.join(st)
- python
leetcode 394. 字符串解码

最新推荐文章于 2024-05-19 22:53:12 发布
