【发布时间】:2017-12-04 08:43:52
【问题描述】:
给定一串数字,计算作为任何回文的字谜的子词(一致子序列)的数量。
我在 Python 中的尝试:
def ispalin(s):
if len(s)%2==0:
for i in s:
if s.count(i)%2!=0:
return False
else:
sum =0
for i in set(s):
if s.count(i)%2==1:
sum = sum+1
if sum == 1:
return True
else:
return False
return True
def solution(S):
# write your code in Python 3.6
count=len(S)
for i in range(len(S)):
for j in range(i+1,len(S)):
if ispalin(S[i:j+1]):
count=count+1
return count
i/o 格式
For example, given:
S = "02002"
the function should return 11.
these are 11 substrings whose anagrams are palindrome
"0", "2", "0", "0", "2", "00", "020", "200", "002", "2002", "02002"
大字符串超出时间限制。如何优化上述代码?
我敢打赌,存在比这更好的解决方案,这就是证明 [图片][1]
【问题讨论】:
-
s.count(i)我会使用collections.Counter以获得更好的速度。你能添加一些测试输入和输出吗? -
@Jean-FrançoisFabre 更新了测试用例,顺便说一句,它的复杂度是 o(n)3 我们必须降低时间复杂度
-
@OmG 我敢打赌,o(n) 中存在解决方案,但我现在不确定
-
在这种情况下,解决方案应该基于某种排列计数。您不能在线性时间内遍历所有子词,因为它们有 O(N^2) 个。
-
@Vovanrock2002 是的,这里的数学很糟糕