我敢肯定,我的if/elif的语句可以改进,但是这是第 件事我能想到的。如果需要,我可以稍后回来。
@ or1426的解决方案会创建一个当前最长的已排序序列的列表,并在发现较长序列时将其复制到longest
。这会在每次找到更长的序列时创建一个新列表,并附加到每个字符的列表中。这在Python中实际上非常快,但请参见下文。
@ Deej的解决方案将当前最长的已排序序列保留在字符串变量中,并且每当找到更长的子字符串(即使它是当前序列的延续)时,子字符串都会保存到列表中。该列表最后有全部排序的原始字符串的子字符串,最长的是通过调用max
找到的。
这里是一个更快的解决方案,只跟踪当前最大序列的指数,当它发现一个字符不按排序顺序只是更改最长:
def bjorn4(s):
# we start out with s[0] being the longest sorted substring (LSS)
longest = (0, 1) # the slice-indices of the longest sorted substring
longlen = 1 # the length of longest
cur_start = 0 # the slice-indices of the *current* LSS
cur_stop = 1
for ch in s[1:]: # skip the first ch since we handled it above
end = cur_stop-1 # cur_stop is a slice index, subtract one to get the last ch in the LSS
if ch >= s[end]: # if ch >= then we're still in sorted order..
cur_stop += 1 # just extend the current LSS by one
else:
# we found a ch that is not in sorted order
if longlen < (cur_stop-cur_start):
# if the current LSS is longer than longest, then..
longest = (cur_start, cur_stop) # store current in longest
longlen = longest[1] - longest[0] # precompute longlen
# since we can't add ch to the current LSS we must create a new current around ch
cur_start, cur_stop = cur_stop, cur_stop+1
# if the LSS is at the end, then we'll not enter the else part above, so
# check for it after the for loop
if longlen < (cur_stop - cur_start):
longest = (cur_start, cur_stop)
return s[longest[0]:longest[1]]
有多快?它几乎是orl1426的两倍,比deej快三倍。一如既往,取决于您的输入。存在的排序子串的块越多,上述算法与其他算法相比就越快。例如。上长度含有交替的100个随机字符和100按顺序字符100000的输入字符串,我得到:
bjorn4: 2.4350001812
or1426: 3.84699988365
deej : 7.13800001144
如果我将其更改为交替的1000个随机字符和1000排序字符,然后我得到:
bjorn4: 23.129999876
or1426: 38.8380000591
deej : MemoryError
更新: 这里是我的算法的进一步优化版本,与比较代码:
import random, string
from itertools import izip_longest
import timeit
def _randstr(n):
ls = []
for i in range(n):
ls.append(random.choice(string.lowercase))
return ''.join(ls)
def _sortstr(n):
return ''.join(sorted(_randstr(n)))
def badstr(nish):
res = ""
for i in range(nish):
res += _sortstr(i)
if len(res) >= nish:
break
return res
def achampion(s):
start = end = longest = 0
best = ""
for c1, c2 in izip_longest(s, s[1:]):
end += 1
if c2 and c1 <= c2:
continue
if (end-start) > longest:
longest = end - start
best = s[start:end]
start = end
return best
def bjorn(s):
cur_start = 0
cur_stop = 1
long_start = cur_start
long_end = cur_stop
for ch in s[1:]:
if ch < s[cur_stop-1]:
if (long_end-long_start) < (cur_stop-cur_start):
long_start = cur_start
long_end = cur_stop
cur_start = cur_stop
cur_stop += 1
if (long_end-long_start) < (cur_stop-cur_start):
return s[cur_start:cur_stop]
return s[long_start:long_end]
def or1426(s):
longest = [s[0]]
current = [s[0]]
for char in s[1:]:
if char >= current[-1]: # current[-1] == current[len(current)-1]
current.append(char)
else:
current=[char]
if len(longest) < len(current):
longest = current
return ''.join(longest)
if __name__ == "__main__":
print 'achampion:', round(min(timeit.Timer(
"achampion(rstr)",
setup="gc.enable();from __main__ import achampion, badstr; rstr=badstr(30000)"
).repeat(15, 50)), 3)
print 'bjorn:', round(min(timeit.Timer(
"bjorn(rstr)",
setup="gc.enable();from __main__ import bjorn, badstr; rstr=badstr(30000)"
).repeat(15, 50)), 3)
print 'or1426:', round(min(timeit.Timer(
"or1426(rstr)",
setup="gc.enable();from __main__ import or1426, badstr; rstr=badstr(30000)"
).repeat(15, 50)), 3)
随着输出:
achampion: 0.274
bjorn: 0.253
or1426: 0.486
改变数据是随机的:
achampion: 0.350
bjorn: 0.337
or1426: 0.565
和分类:
achampion: 0.262
bjorn: 0.245
or1426: 0.503
“不,不,它不是死的,它是静止状态”
尝试'因为我在枚举:'应该工作在我的头顶 – dgBP
“为什么会发生?”提示:如果'[i]'是字符串中的最后一个字符,那么'[i + 1]'是什么? – Kevin
这是因为'for s in s'将从字面上将's'的元素作为一个数组,所以第一个元素将是'c',第二个元素将是'n'等。您想要查找索引,所以你想得到你所在的元素的编号,'enumerate'应该这样做。如果有效,我会将其作为答案发布。 – dgBP