【问题标题】:Why run time error in program?为什么程序运行时错误?
【发布时间】:2018-05-13 18:49:32
【问题描述】:

在 HackerRank 上的一个问题中,要计算回文子串的数量。

这个程序运行良好,尝试了不同的测试用例。

但它没有通过 HackerRank 上的最后两个测试用例。

我的程序未能成功执行的可能的测试用例是什么。

这是问题陈述。

它有 1 个参数:一个字符串,s。它必须返回一个整数,表示 s 的回文子串的数量。

约束

1 ≤ |S| ≤ 5 × (10)^3 s 由小写英文字母组成。

输出格式

您的函数必须返回一个整数,表示 s 的不同回文子串的数量

def countPalindromes(s):
    counter=0
    length = len(s)
    list1= ([s[i:j+1] for i in range(length) for j in range(i,length)])
    list2=([x[::-1] for x in list1])
    for i in range(len(list2)):
        if(list1[i]==list2[i]):
            counter+=1
    return counter

#input = aaa
#output = 6 i.e. {a,a,a,aa,aa,aaa}
#input = abccba
#output = 9
#input = daata
#output = 7
#output is correct though failing the last 2 test cases

【问题讨论】:

  • 这个函数应该做什么?
  • 统计回文子串的总数。看看 End 中的 cmets
  • 你写代码的时候肯定有更详细的规范。现在不可能看到它可能出了什么问题。
  • 挑战的名称是什么?
  • 提供黑客等级网站的链接或其他内容。

标签: python testing palindrome


【解决方案1】:

您可以使用RecursionMemoization 来计算字符串中回文子串的数量。例如:

def is_palindrome(s):
    return 1 if s == s[::-1] else 0


def count_palindromes(s, i, j, m):
    key = '{}-{}'.format(i, j)
    if key in m.keys():
        return m[key]
    if i == len(s)-1 or i > j:
        return 0
    m[key] = is_palindrome(s[i:j]) + count_palindromes(s, i+1, j, m) + count_palindromes(s, i, j-1, m)
    return m[key]


m = {}
print(count_palindromes('aaa', 0, 2, m)) # should be count_palindromes(s, 0, len(s)-1, m)
# output: 6

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多