簡體   English   中英

我找到字符串數組的最長公共前綴的解決方案的時間復雜度

[英]Time complexity of my solution to finding the longest common prefix of an array of strings

我為以下問題編寫了一個解決方案:

Write a function to find the longest common prefix string amongst an array of strings.

If there is no common prefix, return an empty string "".

有人可以幫我分解代碼的時間復雜度嗎? 我首先對數組進行了排序,這使得時間復雜度為 O(n log n)。 然后我循環遍歷輸入數組中最短元素的長度(這會被認為是O(n),然后最后一個while循環遍歷輸入數組的長度。所以我的猜測是O(n)的整體時間復雜度^2)?如果是這樣,是否可以優化我的代碼以使其更快?謝謝!

class Solution:
    def longestCommonPrefix(self, strs: List[str]) -> str:
        strs.sort(key=len)
        longestPrefix = ""
        index = 1
        char = 0
        skip = False
        
        if not strs:
            return ""
        
        for _ in range(len(strs[0])):
            while index < len(strs):
                if strs[0][char] ==  strs[index][char]:
                    index += 1
                else:
                    skip = True
                    break
            if not skip:
                longestPrefix += strs[0][char]
                char += 1
                index = 1
            else:
                break
        
        return longestPrefix

我認為可以在 O(n log n max_str_len) 中實現一個好的解決方案,其中 n 是字符串數,max_str_len 是最大字符串長度。 您不需要檢查列表中的每個字符串,只需檢查第一個和最后一個。 我更改了您的一些代碼:

def longestCommonPrefix(strs) -> str:

len_list = len(strs)
if (len_list == 0): 
    return "" 

if (len_list == 1): 
    return strs[0] 
strs.sort()
longestPrefix = ""
# retrieving the minimum length of the first and last element of the list
min_word_len = min(len(strs[0]), len(strs[len_list - 1])) 

# looking for the common prefix between the first and last string  
i = 0
while (i < min_word_len and strs[0][i] == strs[len_list - 1][i]): 
    i += 1
    
longestPrefix = strs[0][0: i] 
return longestPrefix    

如果您通過並行字符串使用 zip function 到 go 的性能,您應該獲得 O(N*M) 的性能,其中 N 是最短前綴大小,M 是最短前綴大小。

from itertools import takewhile
def commonPrefix(*strings):
    return "".join(c for c,*_ in
                   takewhile(lambda c:all(s==c[0] for s in c),zip(*strings)))

commonPrefix("abcde","abddes","abegh") # "ab"

暫無
暫無

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

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