簡體   English   中英

給定一個字符串和char數組,返回包含char的字符串? 我已經得到O(N ^ 2),但是有沒有一種優化的方法?

[英]Given an array of strings and char, return strings containing char? I've gotten O(N^2), but is there a way to optimize?

給定一個字符串和char數組,是否返回包含char的字符串(沒有內置函數)? 我已經得到O(N ^ 2),但是有沒有一種優化的方法? 也許是一種利用字典的方法? 謝謝! 編輯:字符串未排序/唯一列出。

def find_char(array, char_to_find):
    strings = []
    for i in xrange(len(array)):
        notFound = True
        for j in xrange(len(array[i])):
            if array[i][j] == char_to_find and notFound:
                strings.append(array[i])
                notFound = False
    return strings

array = ['bob', 'yo', 'hello', 'yes']
print find_char(array, 'o')
return [hit for hit in array if char_to_find in hit]

這不符合條件嗎?

另外,您的解決方案如何以O(N ^ 2)的形式出現? 我將其視為O(N * M),其中M是字符串長度的合理統計量,而N是array的長度。


我從復雜性搜索中獲得了更多信息:

  1. in運算符是線性的O(m) (要搜索的字符串的長度)。 在“好的”情況下,它是O(m / t) ,其中t是我們要查找的字符串的長度。 在此應用程序中為1。
  2. 列表理解比append快,但是仍然O(n)
  3. 我們似乎堅持將列表中的每個單詞都單獨考慮: O(n)

剩下的就是O(n ^ 2 * m)

現在...值得實現一個字符串鏈接列表以獲取O(1)插入(列表的前面)嗎? 它具有較高的開銷,但是將復雜度降低為O(n * m)


@Bi Rico,謝謝。 我誤讀了自己的鏈接(為什么還要第二次發布?)。 append實際上是O(n) ,因此原始問題確實具有復雜度O(m * n)

一些技巧。 將字符串轉換為集合,然后檢查集合中的成員身份。 這將成為O(1)運算。 我不知道在運行時間in ,當涉及到字符串(我猜為O(n))。 盡管如此,將每個字符串轉換為集合的時間在字符串的大小上是線性的(如注釋中所指出的),因此盡管通過消除內部的for循環,此方法的運行速度可能比您的解決方案要快,但這並不能保證且漸近運行時間優於O(N ^ 2)

def find_char(array, char_to_find):
        strings = []
        for my_string in array:
            str_chars = set(my_string)
            if char_to_find in str_chars:
                strings += [my_string]
        return strings

    array = ['bob', 'yo', 'hello', 'yes']
    print find_char(array, 'o')

暫無
暫無

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

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