简体   繁体   中英

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

Given an array of strings and char, return strings containing char (no built in functions)? I've gotten O(N^2), but is there a way to optimize? Perhaps a way utilizing a dict? Thanks! Edit: Strings are unsorted/unique to list.

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]

Does this not qualify?

Also, how does your solution come up as O(N^2)? I see it as O(N*M), where M is a fair statistic of the string length, and N is the length of array .


I got more info from the complexity searches:

  1. The in operator is linear, O(m) (length of the string being searched). In "good" cases, it's O(m/t) , where t is length of the string we want to find. That's 1 in this application.
  2. List comprehension is faster than append , but still O(n) .
  3. We seem stuck with taking each word in the list individually: O(n) .

That leaves us still with O(n^2 * m) .

Now ... is it worth implementing a linked list of strings to get O(1) insertion (front of the list)? It has a higher overhead, but drops the complexity to O(n*m) .


@Bi Rico, thanks. I misread my own link (why did you post it a second time?). append is, indeed, O(n) , so the original problem does have complexity O(m*n) .

A few tips. Convert the string into a set and then check for membership in the set. That becomes an O(1) operation. I'm not sure the runtime for in when it comes to strings (I'd guess O(n)). Still, the time to convert the each string to a set is linear in the size of the string (as pointed out in the comments) so while this may run faster than your solution by eliminating the inner for loop, it does not guarantee and asymptotic runtime better than 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')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM