有人问我一个问题
Find the longest alphabetically increasing or equal string
composed of those letters. Note that you are allowed to drop
unused characters.
So ghaaawxyzijbbbklccc returns aaabbbccc.
Is an O(n) solution possible?
我实现了它的代码 [in python]
s = 'ghaaawxyzijbbbklccc'
lst = [[] for i in range(26)]
for ch in s:
ml = 0
for i in range(0,ord(ch) + 1 - ord('a')):
if len(lst[i]) > len(lst[ml]):
ml= i
cpy = ''.join(lst[ml])
lst[ord(ch) - ord('a')] = cpy + ch
ml = 0
for i in range(26):
if len(lst[i]) > len(lst[ml]):
ml = i
print lst[ml]
答案是'aaabbbccc'
我已经尝试了一些更多的例子并且所有的作品!并且据我所知,这段代码的复杂度是 O(N) 让我们举个例子,假设我有一个字符串 'zzzz' 所以主循环将运行 4 次,内部循环将运行 26 次迭代,所以我们可以说在最坏的情况下代码将运行
O(26*N + 26)
---------^-
this is the last iteration
所以 O(N) 可以接受吗?
现在的问题是
- 它是否适用于 O(N)我在 ideone 的代码
- 如果它在 O(N) 中工作,那么为什么要使用 DP 的 O(N2)代码的 DP
- 比这个代码更好吗?朋友代码
- 此代码的限制