fork download
  1. /*
  2.  
  3. Find the longest word which is made of words.
  4.  
  5. list = test, tester, testertest, testing, testingtester, mytestingtesterprogram, testertestingtesting
  6. output = testertestingtesting
  7.  
  8. */
  9.  
  10. #include "bits/stdc++.h"
  11.  
  12. using namespace std;
  13.  
  14. bool isWordMadeOfOtherWords(unordered_set<string>& st, string& word, int index) {
  15. if (index >= word.size()) {
  16. return false;
  17. }
  18. if (index != 0 && (st.find(word.substr(index)) != st.end())) {
  19. return true;
  20. }
  21.  
  22. bool flag = false;
  23. for (int i=index+1;i<word.size();i++) {
  24. if (st.find(word.substr(index, i-index)) != st.end()) {
  25. if (isWordMadeOfOtherWords(st, word, i)) {
  26. flag = true;
  27. break;
  28. }
  29. }
  30. }
  31. return flag;
  32. }
  33.  
  34. string longestWordMadeOfOtherWords(vector<string>& wordlist) {
  35. unordered_set<string> st;
  36. for (auto word : wordlist) {
  37. st.insert(word);
  38. }
  39.  
  40. int maxlen = 0;
  41. string longest_word = "";
  42. for (auto word : wordlist) {
  43. if (maxlen < word.size() && isWordMadeOfOtherWords(st, word, 0)) {
  44. maxlen = word.size();
  45. longest_word = word;
  46. }
  47. }
  48. return longest_word;
  49. }
  50.  
  51. int main() {
  52. vector<string> wordlist = {"testingtest", "test", "testing", "testtesttest"};
  53. cout << longestWordMadeOfOtherWords(wordlist) << endl;
  54.  
  55. wordlist = {"test", "tester", "testertest", "testing", "testingtester", "mytestingtesterprogram", "testertestingtesting"};
  56.  
  57. cout << longestWordMadeOfOtherWords(wordlist) << endl;
  58. }
Success #stdin #stdout 0.01s 5440KB
stdin
Standard input is empty
stdout
testtesttest
testertestingtesting