簡體   English   中英

什么是最快的算法:在字符串列表中,刪除作為另一個字符串的子字符串的所有字符串 [Python(或其他語言)]

[英]What is the fastest algorithm: in a string list, remove all the strings which are substrings of another string [Python (or other language)]

有一個字符串列表,例如 ["abc", "ab", "ad", "cde", "cde", "de", "def"] 我希望 output 是 ["abc", "廣告”、“cde”、“def”]

“ab”被刪除,因為它是“abc”的 substring “cde”被刪除,因為它是另一個“cde”的 substring “de”被刪除,因為它是“def”的 substring

最快的算法是什么?

我有一個蠻力方法,即 O(n^2) 如下:

def keep_long_str(str_list):
    str_list.sort(key = lambda x: -len(x))
    cleaned_str_list = []
    for element in str_list:
        element = element.lower()
        keep_element = 1
        for cleaned_element in cleaned_str_list:
            if element in cleaned_element:
                keep_element = 0
                break
            else:
                keep_element = 1
        if keep_element:
            cleaned_str_list.append(element)
    return cleaned_str_list
strings = ["abc", "ab", "ad", "cde", "cde", "de", "def"]
unique_strings = []

for s in strings: 
     if all(s not in uniq for uniq in unique_strings):
         unique_strings.append(s)

運行此代碼后, unique_strings等於['abc', 'cde', 'def', 'ad']

注意:這可能不是最快的方法,但它是一個簡單的解決方案。

我查看了 Jack Moody 和 Chris Charley 的答案,但仍然不喜歡在第一次出現超弦時使用all when any may break out the loop,所以想出了這個改動:

strings = ["abc", "ab", "ad", "cde", "cde", "de", "def"]
unique_strings = []
for s in sorted(strings, reverse=True):  # Largest first 
    if not any(s in uniq for uniq in unique_strings):
        unique_strings.append(s)
print(unique_strings)  # ['def', 'cde', 'ad', 'abc']

我認為不需要對字符串len進行明確排序,因為無論如何它都是字符串比較的一部分。 干杯:-)

暫無
暫無

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

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