[JS] Longest String Chain
2022. 9. 17. 15:19
🔒 문제 (LeetCode 1048)
You are given an array of words where each word consists of lowercase English letters.
wordA is a predecessor of wordB if and only if we can insert exactly one letter anywhere in wordA without changing the order of the other characters to make it equal to wordB.
- For example, "abc" is a predecessor of "abac", while "cba" is not a predecessor of "bcad".
A word chain is a sequence of words [word1, word2, ..., wordk] with k >= 1, where word1 is a predecessor of word2, word2 is a predecessor of word3, and so on. A single word is trivially a word chain with k == 1.
Return the length of the longest possible word chain with words chosen from the given list of words.
Constraints:
- 1 <= words.length <= 1000
- 1 <= words[i].length <= 16
- words[i] only consists of lowercase English letters.
🌊 입출력
Example 1:
Input: words = ["a","b","ba","bca","bda","bdca"]
Output: 4
Explanation: One of the longest word chains is ["a","ba","bda","bdca"].
Example 2:
Input: words = ["xbc","pcxbcf","xb","cxbc","pcxbc"]
Output: 5
Explanation: All the words can be put in a word chain ["xb", "xbc", "cxbc", "pcxbc", "pcxbcf"].
Example 3:
Input: words = ["abcd","dbqca"]
Output: 1
Explanation: The trivial word chain ["abcd"] is one of the longest word chains.
["abcd","dbqca"] is not a valid word chain because the ordering of the letters is changed.
🔑 해결
🌌 알고리즘 - DP
/**
* @param {string[]} words
* @return {number}
*/
var longestStrChain = function(words) {
words.sort((a, b) => a.length - b.length) // predecessor 찾기 위해 길이 순으로 정렬
let dp = {} // word - word를 만들 수 있는 word chain의 최대 길이
for(const word of words) {
let max = 0;
for(let i = 0; i < word.length; i++) {
// predecessor가 words에 존재하면 기존 chain + 1
// 그렇지 않으면 새로운 chain 시작
const pre = word.slice(0, i) + word.slice(i+1)
max = Math.max(max, (dp[pre] || 0) + 1)
}
dp[word] = max
}
return Math.max(...Object.values(dp))
};
'코딩테스트 (JS) > DP' 카테고리의 다른 글
[JS] Integer Break (0) | 2022.09.23 |
---|---|
[JS] Coin Change (0) | 2022.09.18 |
[JS] Edit Distance (0) | 2022.09.17 |
[JS] Delete Operation for Two Strings (0) | 2022.09.14 |
[JS] Longest Common Subsequence (0) | 2022.09.13 |