【问题标题】:Recursive Sub-Palindrom with length of SubPalindrom具有子回文长度的递归子回文
【发布时间】:2018-12-06 16:07:19
【问题描述】:

我正在尝试制作一个递归函数,它计算最大的子回文数。

例如最大的 sub.Pal。对于“字符”是“carac”。

到目前为止,我已经实现了我的目标,但只是使用了一个全局变量“长度”来添加我的值,但如果有人能告诉我如何只通过递归调用来做到这一点,那就太好了。我首先尝试为函数提供第二个参数(长度 = 0)并在调用函数时为其添加值,但我没有让它正常工作。

这是我的代码:

length = 0

def subpalindrom(s):
    global length
    if len(s) == 1:
        length += 1
        return True, length

    if len(s) == 0:
        return True, length

    elif s[0] != s[-1]:

        for i in range(len(s) - 1, int(len(s) / 2) - 1, -1):  # search right half, if there is smth. equal

        if s[0] == s[i]:
            length += 2
            return subpalindrom(s[1:i])  # if smth. is equal slice it, add length

        elif i == int(len(s) / 2):
            # if index i is at half of the string and nothing was found, continue with next val on left half
            return subpalindrom(s[1:])
    else:
        length += 2
        return subpalindrom(s[1:-1])


print(subpalindrom("character"))

如果有人能告诉我如何查看该函数的时间复杂度,那就太好了。我会说它是 O(log n),但这只是一个猜测。

编辑:T(n) = T(n-2) + n/2 ? T(n-2) 用于递归调用(因为我们切掉了 2 个元素)和 + n/2 因为 for 循环?

感谢您的宝贵时间!

【问题讨论】:

    标签: python python-3.x recursion


    【解决方案1】:

    对不起,迟到的分享,但如果有人有兴趣,我是这样处理的:

    def subpalindrom(l, r, w):
        if l == r:
            return 1
        if l > r:
            return 0
        if w[l] == w[r]:
            return 2 + subpalindrom(l + 1, r - 1, w)
        else:
            return max(subpalindrom(l + 1, r, w), subpalindrom(l, r - 1, w))
    
    
    print(subpalindrom(0, len("character")-1, "character"))
    

    【讨论】:

      猜你喜欢
      • 2021-05-15
      • 2015-07-09
      • 2019-05-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-30
      相关资源
      最近更新 更多