簡體   English   中英

使用預計算優化特定用例的Python算法

[英]Optimizing Python Algorithm for a particular Use Case using Pre-Computing

我正在嘗試解決此處提到的問題的特定變體:

給定字符串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個索引並且存在不保證訂單將被保留。

那么,我堅持如何針對上述用例優化算法?

謝謝你的幫助。

對於每個小於len(t) i ,以及在t中出現的每個字符c ,從(i,c)->j進行映射,其中j是第一個索引> = i ,其中c出現。

然后,您可以使用地圖迭代每個Sk,以查找每個所需字符的下一個匹配項(如果存在)。

這實際上是一個確定性的有限自動機,它匹配t序列( https://en.wikipedia.org/wiki/Deterministic_finite_automaton )。

您可以預處理t以創建所有可能子序列的列表(請記住, t將具有2^len(t)-1序列)。 您可以將其轉換為哈希表,然后遍歷您的s列表,檢查表中的每個s 優點是你不必為每個s迭代t

順便說一句,如果你在預處理t上遇到所有子序列的列表,你應該研究一下powerset及其在python中的實現。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM