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)
I'm working on leetcode problem 394 decoding string problem the problem is to convert a string.
- s = "3[a]2[bc]", return "aaabcbc".
- s = "3[a2[c]]", return "accaccacc".
- s = "2[abc]3[cd]ef", return "abcabccdcdcdef".
The above solution is a Python version which was translated from author bluedawnstar cpp solution.
self.i is maintaining the global state throughout the recursion, is there a more Pythonic way to maintaining such variable instead using self?