Advertisement
Guest User

Untitled

a guest
Aug 20th, 2019
77
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.13 KB | None | 0 0
  1. function longestChain(words) {
  2. let sortedWords = words.sort((a, b) => b.length - a.length);
  3. let wordSet = new Set(sortedWords);
  4. let longestChain = 0;
  5.  
  6. function funcRecur(wordRecur, count) {
  7.  
  8. // console.log('wordRecur: ', wordRecur, ' count: ', count);
  9.  
  10. if (wordRecur.length <= 1) {
  11. // console.log('this is what gets returned: ', count);
  12. return count;
  13. };
  14.  
  15. let shortened = '';
  16. let foundPath = false;
  17. for (let i = 0; i < wordRecur.length; i++) {
  18. shortened = wordRecur.slice(0, i) + wordRecur.slice(i + 1, wordRecur.length);
  19.  
  20. if (wordSet.has(shortened)) {
  21. foundPath = true;
  22. return funcRecur(shortened, count + 1);
  23. }
  24. }
  25.  
  26. if (!foundPath) {
  27. return count;
  28. }
  29. }
  30.  
  31.  
  32. let countForWord = 0;
  33. for (let word of sortedWords) {
  34. countForWord = funcRecur(word, 1);
  35. console.log(`${word}: `, countForWord);
  36. longestChain = countForWord > longestChain ? countForWord : longestChain;
  37. }
  38.  
  39. return longestChain;
  40. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement