Given a dictionary and a list of letters find all valid words that can be built with the letters

前端 未结 12 889
闹比i
闹比i 2021-01-31 12:26

The brute force way can solve the problem in O(n!), basically calculating all the permutations and checking the results in a dictionary. I am looking for ways to improve the com

12条回答
  •  旧巷少年郎
    2021-01-31 12:53

    Swift 4

    func findValidWords(in dictionary: [String], with letters: [Character]) -> [String] {
        var validWords = [String]()
    
        for word in dictionary {
            var temp = word
            for char in letters {
                temp = temp.filter({ $0 != char })
    
                if temp.isEmpty {
                    validWords.append(word)
                    break
                }
            }
        }
    
        return validWords
    }
    

    print(findValidWords(in: ["ape", "apples", "orange", "elapse", "lap", "soap", "bar", "sole"], with: ["a","p","l","e","s","o"]))

    Output => ["ape", "apples", "elapse", "lap", "soap", "sole"]

提交回复
热议问题