Closed. This question needs details or clarity。它当前不接受答案。
                            
                        
                    
                
                            
                                
                
                        
                            
                        
                    
                        
                            想改善这个问题吗?添加详细信息并通过editing this post阐明问题。
                        
                        去年关闭。
                                                                                            
                
        
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在整个递归中都保持全局状态,是否有更多的Python方式来维护此类变量而不是使用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

10-06 13:50