Created
May 17, 2021 15:45
-
-
Save vrat28/abc10f2a200e91012196f3a5da4ce1b5 to your computer and use it in GitHub Desktop.
Longest String Chain(Python - Bottom Up)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution: | |
def longestStrChain(self, words: List[str]) -> int: | |
words.sort(key=len) # sort words by its length | |
ans = 0 | |
cnt = defaultdict(int) | |
for word in words: | |
cnt[word] = 1 | |
for i in range(len(word)): | |
predecessor = word[:i] + word[i+1:] | |
if predecessor in cnt and cnt[word] < cnt[predecessor] + 1: | |
cnt[word] = cnt[predecessor] + 1 | |
ans = max(ans, cnt[word]) | |
return ans |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment