python - k个连续字符串中最长的
问题描述
我正在定义一个 Python 函数来确定最长的字符串,如果原始字符串针对每 k 个连续字符串进行组合。该函数有两个参数,strarr
和k
。
这是一个例子:
max_consec(["zone", "abigail", "theta", "form", "libe", "zas", "theta", "abigail"], 2) --> "abigailtheta"
到目前为止,这是我的代码(本能是我没有k
在函数中正确传递)
def max_consec(strarr, k):
lenList = []
for value in zip(strarr, strarr[k:]):
consecStrings = ''.join(value)
lenList.append(consecStrings)
for word in lenList:
if max(word):
return word
这是一个未通过的测试用例:
testing(longest_consec(["zone", "abigail", "theta", "form", "libe", "zas"], 2), "abigailtheta"
)
我的输出:
'zonetheta' should equal 'abigailtheta'
解决方案
将字符串长度存储在数组中。现在假设一个大小为 k 的窗口通过这个列表。跟踪此窗口中的总和和窗口的起点。
当窗口到达数组的末尾时,您应该有最大的总和和出现最大值的索引。使用此窗口中的元素构造结果。
时间复杂度:O(数组大小+所有字符串大小之和)~O(n)
还添加一些极端情况处理 whenk > array_size
或k <= 0
def max_consec(strarr, k):
size = len(strarr)
# corner cases
if k > size or k <= 0:
return "None" # or None
# store lengths
lenList = [len(word) for word in strarr]
print(lenList)
max_sum = sum(lenList[:k]) # window at index 0
prev_sum = max_sum
max_index = 0
for i in range(1, size - k + 1):
length = prev_sum - lenList[i-1] + lenList[i + k - 1] # window sum at i'th index. Subract previous sum and add next sum
prev_sum = length
if length > max_sum:
max_sum = length
max_index = i
return "".join(strarr[max_index:max_index+k]) # join strings in the max sum window
word = max_consec(["zone", "abigail", "theta", "form", "libe", "zas", "theta", "abigail"], 2)
print(word)
推荐阅读
- jpanel - 试图将面板投射到 JOptionPane
- delphi - 启动(调试)32 位应用程序时,Delphi 10.2.3 挂起
- node.js - KeyCloak 和 passportjs-saml - 无法完成 SAML 流程
- python - 无法为使用 zeep 创建的肥皂客户端创建请求 xml
- java - GridPane 未居中对齐
- javascript - 如何使用流检索函数参数类型
- javascript - JS - 下载与 Node.js 交互的完整触发器
- visual-studio-code - 如何配置 Prettier 格式化程序 - vscode 插件与安装的 npm 模块不一致
- java - 既然 tools.jar 在 Java 9 中被分解,sun.misc.Perf 移动到哪里了
- django - Django ModelForm - 防止保存在视图中