递归函数中的Python类变量

标签 python variables recursion class-variables

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/

相关文章:

javascript - 使用递归返回嵌套对象 - Javascript

sql - 如何递归查找 child 的所有ID?

python - 我不明白这个 Django 文档。我该如何使用这个模块?

python ObjectListView 有一个不可编辑的列

bash - 将数字字符串格式化为日期

javascript - jQuery - 在变量元素内引用伪/其他类

c++ - C++ 构造函数\析构函数中的奇怪行为

python - 使用 argmax 在 tensorflow 中切片张量

python - 如何在 SPOJ 问题硬币中使用 Python 输入?

python - 如何在pygame中存储对象先前的x位置(坐标)?