【发布时间】:2021-01-26 18:30:44
【问题描述】:
我正在解决 Leetcode 问题,以查找字符串中最长的回文子串。这是我的代码。
def longest_palindrome_substring(string):
array = [i for i in string]
# keep track of which substrings are palindromes
s = [[None for _ in range(len(array))] for _ in range(len(array))]
# longest substring so far
best = ""
# look at successively larger substrings
for substring_length in range(len(array)): # is actually substring length - 1 = stop - start
# look at the substring from start to stop, inclusive
for start, stop in zip(range(len(array) - substring_length), [x + substring_length for x in range(len(array) - substring_length)]):
# is it a palindrome?
if start == stop:
is_p = True
elif array[start] == array[stop]:
if start + 1 == stop:
is_p = True
else:
is_p = s[start + 1][stop - 1]
else:
is_p = False
# store result
s[start][stop] = is_p
# is it the best so far?
if is_p:
if substring_length + 1 > len(best):
best = array[start:stop + 1]
return "".join(best)
我得到了所有问题的正确答案,但它说这段代码太慢了。我该怎么做才能加快速度?
我试图关注strategy outlined here。
【问题讨论】:
-
除了寻找最佳算法之外,如果您想分析自己的代码以了解其大部分时间花在哪里,请参阅How to Use Python Profilers。
-
这可能更适合CodeReview
标签: python performance dynamic-programming