diff options
author | jack <[email protected]> | 2024-06-14 13:13:15 -0600 |
---|---|---|
committer | jack <[email protected]> | 2024-06-14 13:13:15 -0600 |
commit | d343a3b18dbaca9297d4f7b2280c4a16f0a5c8aa (patch) | |
tree | 96df922dae2a5073d9a50ea70c7aae6aa37e3ebe /longest_string_chain.py | |
download | leetcode-d343a3b18dbaca9297d4f7b2280c4a16f0a5c8aa.tar.gz leetcode-d343a3b18dbaca9297d4f7b2280c4a16f0a5c8aa.zip |
initial
Diffstat (limited to 'longest_string_chain.py')
-rw-r--r-- | longest_string_chain.py | 25 |
1 files changed, 25 insertions, 0 deletions
diff --git a/longest_string_chain.py b/longest_string_chain.py new file mode 100644 index 0000000..954fe23 --- /dev/null +++ b/longest_string_chain.py @@ -0,0 +1,25 @@ +# 1048. Longest String Chain + +""" +you are given an array of 'words' where each word consists of lowercase +english letters. 'word[a]' is a predecessor of 'word[b]' if and only if we +can insert exactly one letter anywhere in 'word[a]' without changing the +order of the other characters to make it equal to 'word[b]'. return the +length of the longest possible word chain with words chosen from the given +list of words. +""" + + +class Solution(object): + def longestStrChain(self, words): + dp = {} + for w in sorted(words, key=len): + dp[w] = max(dp.get(w[:i] + w[i + 1 :], 0) + 1 for i in xrange(len(w))) + return max(dp.values()) + + +if __name__ == "__main__": + obj = Solution() + print(obj.longestStrChain(["a", "b", "ba", "bca", "bda", "bdca"])) # expect: 4 + print(obj.longestStrChain(["xbc", "pcxbcf", "xb", "cxbc", "pcxbc"])) # expect: 5 + print(obj.longestStrChain(["abcd", "dbqca"])) # expect: 1 |