5.7 Given A list of words, write a program to find the longest word made of other words in the list.
This problem gives us a string array that lets us find the longest word that is made up of other words in the string array, leetcode with Word break and word break II on a similar topic. So, first of all, we think that if we were to split two words, we would first put all the words into the hash table, then iterate through each word, split it into the left and right two strings at each location, and see if they all exist in the hash tables, all of which indicate that the word meets the requirements. So for the split into multiple words, I can use the recursive return to do, we first to order the word group, the length of the long in front, we need to use a hash table to establish a word and whether it can be split between the Boolean value of the mapping, but also useful a variable Is_original_ Word indicates whether the word is a word group word or a word that is split in the recursive process, and then iterates through the word from the beginning, and for each word, we split the left and right sides from each position, and if the word on the other side exists in the hash table and it can be split, then we recursively call the word If all the split methods are complete and the word cannot be broken into an existing word, then the value in its hash table is assigned to false.
BOOLCan_build_word (stringWordBOOLIs_original_word, unordered_map<string,BOOL> &m) {if(M.count (Word) &&!is_original_word)returnM[word]; for(inti =1; I < word.size (); ++i) {stringleft = Word.substr (0, i); stringright =word.substr (i); if(M.count (left) && M[left] && Can_build_word (right,false, M)) { return true; }} M[word]=false; return false;}stringPrint_longest_word (vector<string> &words) {Unordered_map<string,BOOL>m; for(Auto a:words) m[a] =true; Sort (Words.begin (), Words.end (), [] (Const string&a,Const stringb) {returnA.size () >b.size ();}); for(Auto a:words) {if(Can_build_word (A,true, M)) { returnA; } } return "";}
Careercup all in one topic summary
[Careercup] 18.7 longest word longest word