标签:tchar isa break append tmp 存储 组合 pre com
题目描述:按照规定,把字符串解码,具体示例见题目链接
注意4: 不用字符串而用字母栈的原因是字符串的 join 效率会比字符串加法高一些
结果: 30 ms, beat 98.02%
缺点:判断是数字那里有点代码不简洁,可以把 j 挪到循环外面的
class Solution(object):
def decodeString(self, s):
"""
:type s: str
:rtype: str
"""
nums, chars = [], []
i, length = 0, len(s)
while i < length:
j = i + 1
if s[i].isdigit():
num = int(s[i])
while j < length:
if s[j].isdigit():
num = num * 10 + int(s[j])
j += 1
else:
break
nums.append(num)
elif s[i] == ‘[‘ or s[i].isalpha():
chars.append(s[i])
else:
t, tmpc = chars.pop(), []
while t != ‘[‘:
tmpc.append(t)
t = chars.pop()
tchars = nums.pop() * ‘‘.join(tmpc[::-1])
chars.append(tchars)
i = j
return ‘‘.join(chars)
Python 解LeetCode:394 Decode String
标签:tchar isa break append tmp 存储 组合 pre com
原文地址:https://www.cnblogs.com/qiaojushuang/p/9048675.html