【发布时间】:2014-09-30 23:15:37
【问题描述】:
我的 python 似乎在输入字符串的长度不大的情况下工作,但它在相当长的字符串下失败了。这是问题陈述:
如果字符串 S 满足以下两个属性,则称其为特殊字符串: S 中的每个字符都是“0”或“1”。 每当 S = UV 且 U 和 V 都是非空字符串时,U 按字典顺序严格小于 V。 例如,字符串 S = "00101" 是特殊的,因为我们有 "0"
这是我的python代码:
class SpecialStrings(object):
def findNext(self, current):
if current == '0':
return '1'
N = len(current)
iter_times = 2 ** N - int(current, 2) - 1
temp_current = current
for i in range(iter_times):
temp_s = self.get_next_string(temp_current)
if self.is_special(temp_s):
return temp_s
if temp_s[0] == '1':
return ''
temp_current = temp_s
return ''
def get_next_string(self, s):
next_string = bin(int(s, 2) + 1)
next_string = next_string[2:]
if len(next_string) < len(s):
temp_zero = '0' * (len(s) - len(next_string))
next_string = temp_zero + next_string
return next_string
def is_special(self, s):
for i in range(1, len(s)):
left = s[:i]
right = s[i:]
if left >= right:
return False
return True
我收到输入“0111111111111111111111111111”和“001111111111111111111111111111111111111111”的异常终止。当我尝试使用其中任何一个进行本地测试时,我的计算机内存已耗尽......
这里有什么问题?是不是因为我的算法效率不高?如何解决?
非常感谢!!!!!!
【问题讨论】:
-
这是林登的话。见en.wikipedia.org/wiki/Lyndon_word。