Question
Given a list of words, each word consists of English lowercase letters.
Let's say word1 is a predecessor of word2 if and only if we can add exactly one letter anywhere in word1 to make it equal to word2. For example, "abc" is a predecessor of "abac".
A word chain is a sequence of words [word_1, word_2, ..., word_k] with k >= 1, where word_1 is a predecessor of word_2, word_2 is a predecessor of word_3, and so on.
Return the longest possible length of a word chain with words chosen from the given list of words.
Example 1:
Note:
Solution
Naive
- from collections import defaultdict
- class Solution:
- def longestStrChain(self, words: List[str]) -> int:
- # 0) Preprocess
- wdict = defaultdict(list) # key as length of word; value as list of word
- for w in words:
- w_len = len(w)
- wdict[w_len].append(''.join(sorted(list(w))))
- # 1) Start algorithm
- max_wc = 1
- ''' longest word chain'''
- def is_one_char_away(w, nw):
- nw_i = 0
- try:
- for i in range(len(w)):
- if w[i] == nw[nw_i]:
- nw_i += 1
- elif w[i] == nw[nw_i+1]:
- nw_i += 2
- else:
- return False
- except:
- return False
- return True
- visited_wc = set()
- def search_wc(w_len, w, wc):
- wc_len = len(wc)
- next_w_len = w_len + 1
- for nw in wdict[next_w_len]:
- if is_one_char_away(w, nw):
- new_wc = []
- new_wc.extend(wc)
- new_wc.append(nw)
- _wc_len = search_wc(next_w_len, nw, new_wc)
- if _wc_len > wc_len:
- wc_len = _wc_len
- return wc_len
- for w_len in sorted(wdict.keys())[:-1]:
- for w in wdict[w_len]:
- wc_len = search_wc(w_len, w, [w])
- if wc_len > max_wc:
- max_wc = wc_len
- return max_wc
Discussion: dp soluiton (link)
- from collections import defaultdict
- class Solution:
- def longestStrChain(self, words: List[str]) -> int:
- words = sorted(words,key=lambda x:len(x))
- dp = [1]*len(words)
- record = {}
- for i, word in enumerate(words):
- for j in range(len(word)):
- predecessor = word[:j]+word[j+1:]
- if predecessor in record:
- dp[i] = max(dp[record[predecessor]]+1,dp[i])
- record[word] = i
- return max(dp)
Supplement
* 知呼 - 1048. Longest String Chain
* LeetCode 1048. Longest String Chain Explanation and Solution (happygirlzt)
沒有留言:
張貼留言