Skip to content

Commit 2a9e0f7

Browse files
committedApr 2, 2025
Add solution #1048
1 parent 5971704 commit 2a9e0f7

File tree

2 files changed

+46
-1
lines changed

2 files changed

+46
-1
lines changed
 

‎README.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
# 1,119 LeetCode solutions in JavaScript
1+
# 1,120 LeetCode solutions in JavaScript
22

33
[https://leetcodejavascript.com](https://leetcodejavascript.com)
44

@@ -854,6 +854,7 @@
854854
1044|[Longest Duplicate Substring](./solutions/1044-longest-duplicate-substring.js)|Hard|
855855
1046|[Last Stone Weight](./solutions/1046-last-stone-weight.js)|Easy|
856856
1047|[Remove All Adjacent Duplicates In String](./solutions/1047-remove-all-adjacent-duplicates-in-string.js)|Easy|
857+
1048|[Longest String Chain](./solutions/1048-longest-string-chain.js)|Medium|
857858
1051|[Height Checker](./solutions/1051-height-checker.js)|Easy|
858859
1071|[Greatest Common Divisor of Strings](./solutions/1071-greatest-common-divisor-of-strings.js)|Easy|
859860
1072|[Flip Columns For Maximum Number of Equal Rows](./solutions/1072-flip-columns-for-maximum-number-of-equal-rows.js)|Medium|
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
/**
2+
* 1048. Longest String Chain
3+
* https://leetcode.com/problems/longest-string-chain/
4+
* Difficulty: Medium
5+
*
6+
* You are given an array of words where each word consists of lowercase English letters.
7+
*
8+
* wordA is a predecessor of wordB if and only if we can insert exactly one letter anywhere in
9+
* wordA without changing the order of the other characters to make it equal to wordB.
10+
*
11+
* For example, "abc" is a predecessor of "abac", while "cba" is not a predecessor of "bcad".
12+
*
13+
* A word chain is a sequence of words [word1, word2, ..., wordk] with k >= 1, where word1 is
14+
* a predecessor of word2, word2 is a predecessor of word3, and so on. A single word is
15+
* trivially a word chain with k == 1.
16+
*
17+
* Return the length of the longest possible word chain with words chosen from the given list
18+
* of words.
19+
*/
20+
21+
/**
22+
* @param {string[]} words
23+
* @return {number}
24+
*/
25+
var longestStrChain = function(words) {
26+
const map = new Map();
27+
let result = 1;
28+
29+
words.sort((a, b) => a.length - b.length);
30+
31+
for (const word of words) {
32+
let currentLength = 1;
33+
for (let i = 0; i < word.length; i++) {
34+
const prev = word.slice(0, i) + word.slice(i + 1);
35+
if (map.has(prev)) {
36+
currentLength = Math.max(currentLength, map.get(prev) + 1);
37+
}
38+
}
39+
map.set(word, currentLength);
40+
result = Math.max(result, currentLength);
41+
}
42+
43+
return result;
44+
};

0 commit comments

Comments
 (0)
Please sign in to comment.