class Solution(object):
def decode(self, s):
sub_s = ""
while self.i < len(s) and s[self.i] != "]":
if not s[self.i].isdigit():
sub_s += s[self.i]
self.i += 1
else:
n = 0
while self.i < len(s) and s[self.i].isdigit():
n = n * 10 + int(s[self.i])
self.i += 1
self.i += 1
seq = self.decode(s)
self.i += 1
sub_s += seq * n
return sub_s
def decodeString(self, s):
self.i = 0
return self.decode(s)
我正在研究leetcode问题394解码字符串问题,问题是转换字符串。
- s =“3[a]2[bc]”,返回“aaabcbc”。
- s = "3[a2[c]]", 返回“accaccacc”。
- s = "2[abc]3[cd]ef", 返回 "abcabccdcdcdef"。
上述解决方案是Python版本,由作者bluedawnstar cpp解决方案翻译而来。
self.i
在整个递归过程中维护全局状态,是否有更 Pythonic 的方法来维护此类变量,而不是使用 self
?
最佳答案
您可以使用以下函数,而不需要类变量:
def decode(s):
repeat = output = ''
index = 0
while index < len(s):
char = s[index]
index += 1
if char.isdigit():
repeat += char
elif char == '[':
substring, offset = decode(s[index:])
output += substring * int(repeat)
index += offset
repeat = ''
elif char == ']':
break
else:
output += char
return output, index
def decodeString(s):
return decode(s)[0]
这样:
print(decodeString("3[a]2[bc]"))
print(decodeString("3[a2[c]]"))
print(decodeString("2[abc]3[cd]ef"))
输出:
aaabcbc
accaccacc
abcabccdcdcdef
关于递归函数中的Python类变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53306848/