Find the longest word given a collection

前端 未结 9 1581
既然无缘
既然无缘 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:52

    Groovy (almost Java):

    def letters = ['a', 'e', 'f', 'f', 'g', 'i', 'r', 'q']
    def dictionary = ['abacus', 'deltoid', 'gaff', 'giraffe', 'microphone', 'reef', 'qar']
    println dictionary
        .findAll{ it.toList().intersect(letters).size() == it.size() }
        .sort{ -it.size() }.head()
    

    The choice of collection type to hold the dictionary is irrelevant to the algorithm. If you're supposed to implement a trie, that's one thing. Otherwise, just create one from an appropriate library to hold the data. Neither Java nor Groovy has one in its standard library that I'm aware of.

提交回复
热议问题