LeetCode: Longest String Chain Solution

1/**
2 * @param {string[]} words
3 * @return {number}
4 */
5var longestStrChain = function (words) {
6 const setWords = new Set(words)
7 const memo = {}
8
9 const recursion = word => {
10 if (memo[word] !== undefined) return memo[word]
11 if (setWords.has(word) === false) return 0
12
13 let max = -Infinity
14 for (let i = 0; i < word.length; i++) {
15 max = Math.max(
16 max,
17 1 + recursion(word.substring(0, i) + word.substring(i + 1))
18 )
19 }
20
21 return (memo[word] = max)
22 }
23
24 return Math.max.apply(null, words.map(recursion))
25}

Comments

Loading comments...

Tags

leetcode

hash table

dynamic programming

Apply and earn a $2,500 bonus once you're hired on your first job!

Clients from the Fortune 500 to Silicon Valley startups

Choose your own rate, get paid on time

From hourly, part-time, to full-time positions

Flexible remote working environment

A lot of open JavaScript jobs!!

Fact corner: Referred talent are 5x more likely to pass the Toptal screening process than the average applicant.

Still hesitate? Read HoningJS author's guide on dealing with Toptal interview process.

Next Post

LeetCode: Find Duplicate File In System

May 19, 2021

Previous Post

HoningJS

Search Posts