일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | |||
5 | 6 | 7 | 8 | 9 | 10 | 11 |
12 | 13 | 14 | 15 | 16 | 17 | 18 |
19 | 20 | 21 | 22 | 23 | 24 | 25 |
26 | 27 | 28 | 29 | 30 | 31 |
Tags
- kaggle
- DWG
- LeetCode
- concurrency
- 30. Substring with Concatenation of All Words
- Decorator
- t1
- 밴픽
- attribute
- Protocol
- 715. Range Module
- 파이썬
- 315. Count of Smaller Numbers After Self
- 시바견
- Python
- Python Code
- 운영체제
- Generator
- 프로그래머스
- Class
- Regular Expression
- 109. Convert Sorted List to Binary Search Tree
- 43. Multiply Strings
- Convert Sorted List to Binary Search Tree
- shiba
- 컴퓨터의 구조
- Substring with Concatenation of All Words
- iterator
- data science
- Python Implementation
Archives
- Today
- Total
Scribbling
LeetCode: 1048. Longest String Chain 본문
class Solution:
def longestStrChain(self, words: List[str]) -> int:
ret = 1
# First, we sort words by its length
# By this way, we only need to check the previous length (or current length - 1)
# That is, if the length(word) is k,
# We only need to check words that have length of k - 1.
words.sort(key=lambda word: len(word))
# dp[word]: max chain length until the word
dp = {}
for word in words:
# if length(word) == 1, max chain length = 1
dp[word] = 1
if len(word) == 1:
continue
# Now, how do we know whether word1 (length k + 1) and word2 (length k) are connected or not?
# I think one of the most efficient way is,
# eliminating every character one by one in word1 and check whether it is valid
# e.g. word1 = 'abcde'
# then, check whether 'bcde', 'acde', 'abde', 'abce', 'abcd' are valid
for i in range(len(word)):
temp = word[:i] + word[i+1:]
if temp in dp:
dp[word] = max(dp[word], dp[temp]+1)
ret = max(ret, dp[word])
return ret
'Computer Science > Coding Test' 카테고리의 다른 글
LeetCode: 1284. Minimum Number of Flips to Convert Binary Matrix to Zero Matrix (0) | 2022.03.04 |
---|---|
LeetCode: 715. Range Module (0) | 2022.03.03 |
LeetCode: 990. Satisfiability of Equality Equations (0) | 2022.02.26 |
LeetCode: 652. Find Duplicate Subtrees (0) | 2022.02.23 |
LeetCode: 465. Optimal Account Balancing (0) | 2022.02.17 |