在这里,我必须删除字符串中最频繁的字母表(如果两个字母表的频率相同,则按字母顺序排列),然后将其放入新字符串中。你知道吗
输入:
abbcccdddd
输出:
dcdbcdabcd
我写的代码是:
s = list(sorted(<the input string>))
a = []
for c in range(len(s)):
freq =[0 for _ in range(26)]
for x in s:
freq[ord(x)-ord('a')] += 1
m = max(freq)
allindices = [p for p,q in enumerate(freq) if q == m]
r = chr(97+allindices[0])
a.append(r)
s.remove(r)
print''.join(a)
但它超过了允许的运行时限制,可能是因为循环太多了
我希望有人能推荐一个更优化的版本,使用更少的内存空间。你知道吗
你的解决方案包括26个线性扫描的字符串和一堆不必要的 计算频率的转换。通过使用线性计数步骤替换所有线性扫描、另一个线性重复生成、排序以对字母进行排序以及最后的线性传递以进行条带计数,可以节省一些工作:
更新:我突然想到,我原来的解决方案可以变得更加简洁,实际上是一行程序(不包括所需的导入),它最小化了临时性,而支持单一的按键排序操作,该操作使用一种技巧,按到目前为止看到的每个字母的计数对每个字母进行排序:
这实际上是与原始答案相同的基本逻辑,它只是通过让
sorted
隐式地执行值的修饰和取消修饰来完成,而不是自己显式地执行(隐式修饰/取消修饰是sorted
的key
参数的全部要点;它为您执行Schwartzian transform)。你知道吗就性能而言,这两种方法都是相似的;它们(在实践中)对于较小的输入都是线性扩展的(一个线性扩展到大约150个字符长的输入,较长的代码,使用
Counter
,最大扩展到len
2000范围内的输入),虽然在这一点上增长是超线性的,但它总是低于理论O(n log_2 n)
(可能是由于由于计数和有限的字母表,数据不是完全随机的,因此确保Python的TimSort有一些现有的顺序可以利用)。对于较小的字符串(len
100或更少),一行代码的速度要快一些,对于较大的字符串,较长的代码的速度要快一些(我猜这与较长的代码通过对每个字母的计数运行进行分组来创建一些排序有关)。实际上,除非输入字符串是巨大的,否则这并不重要。你知道吗这个怎么样? 我正在使用内置的python函数来消除循环并提高效率。你知道吗
因为字母表总是固定的26个字符, 这将在O(N)中工作,并且只需要26的常量空间
相关问题 更多 >
编程相关推荐