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

前端 未结 12 1158
闹比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:34

    Swift 3

     func findValidWords(wordsList: [String] , string: String) -> [String]{
    
        let charCountsDictInTextPassed = getCharactersCountIn(string: string)
        var wordsArrayResult: [String] = []
    
        for word in wordsList {
    
            var canBeProduced = true
            let currentWordCharsCount = getCharactersCountIn(string: word)
    
            for (char, count) in currentWordCharsCount {
                if let charCountInTextPassed = charCountsDictInTextPassed[char], charCountInTextPassed >= count {
                    continue
                }else{
                    canBeProduced = false
                    break
                }
            }// end for
    
            if canBeProduced {
                wordsArrayResult.append(word)
            }//end if
        }//end for
            return wordsArrayResult
    }
    
    
    // Get the count of each character in the string
    func getCharactersCountIn(string: String) -> [String: Int]{
        var charDictCount:[String: Int] = [:]
        for char in string.characters {
            if let count = charDictCount[String(char)] {
                charDictCount[String(char)] = count + 1
            }else{
                charDictCount[String(char)] = 1
            }
        }//end for
        return charDictCount
    }
    

提交回复
热议问题