【发布时间】:2018-02-27 17:28:18
【问题描述】:
我正在尝试解决此处提到的问题的特定变体:
给定一个字符串 s 和一个字符串 t,检查 s 是否是 t 的子序列。
我写了一个算法,可以很好地解决上述问题:
def isSubsequence(s, t):
"""
:type s: str
:type t: str
:rtype: bool
"""
i = 0
for x in t:
if i<len(s) and x==s[i]:
i = i + 1
return i==len(s)
现在有一个特定的用例:
如果有很多传入的 S,比如说 S1, S2, ... , Sk 其中 k >= 10 亿,并且你想一一检查 T 是否有它的子序列。
有个提示:
/**
* If we check each sk in this way, then it would be O(kn) time where k is the number of s and t is the length of t.
* This is inefficient.
* Since there is a lot of s, it would be reasonable to preprocess t to generate something that is easy to search for if a character of s is in t.
* Sounds like a HashMap, which is super suitable for search for existing stuff.
*/
但是逻辑似乎颠倒了上述算法的逻辑,如果遍历 s 并使用 hashmap 在 t 中搜索字符,它并不总是正确的,因为 t 的 hashmap 将只有 1 个索引该字符并且无法保证订单会被保留。
那么,我被困在如何针对上述用例优化算法?
感谢您的帮助。
【问题讨论】:
-
t和s的预期大小是多少? -
t 可能非常大,s 必须小于 t 才能使子序列属性有效。
标签: python algorithm data-structures hash hashmap