Find the longest word given a collection

前端 未结 9 1577
既然无缘
既然无缘 2021-01-30 14:03

It is a google interview question and I find most answers online using HashMap or similar data structure. I am trying to find a solution using Trie if possible. Anybody could gi

9条回答
  •  北海茫月
    2021-01-30 14:55

    The first thing to note is that you can completely ignore the letter order.

    Have a trie (well, sort of a trie) as follows:

    • From the root, have 26 children (maximum), one for each letter.
    • From each non-root node have children equal to the number of letters greater or equal to the node's letter.
    • Have each node store all words that can be made using (exactly) the letters in the path from the root.

    Build the trie like this:

    For each word, sort the letters of this word and insert the sorted letters into the trie (by creating a path of these letters from the root), creating all required nodes as you go. And store the word at the final node.

    How to do a look-up:

    For a given set of letters, lookup all subsets of letter (most of which hopefully won't exist) and output the words at each node encountered.

    Complexity:

    O(k!), where k is the number of supplied letters. Eek! But luckely the less words there are in the trie, the less of the paths will exist and the less time this will take. And k is the number of supplied letters (which should be relatively small), not the number of words in the trie.

    Actually it may be more along the lines of O(min(k!,n)), which looks a lot better. Note that if you're given enough letters, you'll have to look up all words, thus you have to do O(n) work in the worst case, so, in terms of the worst case complexity, you can't do much better.

    Example:

    Input:

    aba
    b
    ad
    da
    la
    ma
    

    Sorted:

    aab
    b
    ad
    ad
    al
    am
    

    Trie: (just showing non-null children)

         root
         /  \
        a    b
     /-/|\-\
    a b d l m
    |
    b
    

    Lookup of adb:

    • From the root...
    • Go to child a
      • Go to child b
        • No children, return
      • Go to child d
        • Output words at node - ad and da
        • No children, return
      • All letters processed, return
    • Go to child b
      • Output words at node - b
      • Not looking for a child, as only children >= b exists
      • No d child, return
    • No d child, stop

提交回复
热议问题