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".

word chain is a sequence of words [word_1, word_2, ..., word_k] with k >= 1, where word_1 is a predecessor of word_2word_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:

Input: ["a","b","ba","bca","bda","bdca"]
Output: 4
Explanation: one of the longest word chain is "a","ba","bda","bdca".
class Solution {
public int longestStrChain(String[] words) {
Arrays.sort(words, (a, b) -> a.length() - b.length());
// map is used as space for dp best[i] = 1 + best[i- 1]
Map<String, Integer> map = new HashMap<>();
int res = 0;
for (String word: words) {
map.put(word, 1);
for (int i = 0; i < word.length(); i++) {
String prev = word.substring(0, i) + word.substring(i + 1);
int curLen = map.get(word);
if (map.containsKey(prev) && map.get(prev) + 1 > curLen) {
map.put(word, map.get(prev) + 1);
}
}
res = Math.max(res, map.get(word));
}
return res;
}
}

最新文章

  1. [LeetCode] Reverse Words in a String II 翻转字符串中的单词之二
  2. Linux新手扫盲(转载)
  3. 【51Nod 1616】【算法马拉松 19B】最小集合
  4. 详细了解HTML标签内容模型
  5. 【UWP】UI适配整理
  6. Android onTouchEvent, onClick及onLongClick的调用机制
  7. Python笔记(一)
  8. Jquery图片放大镜
  9. poj 1328 Radar Installation(贪心)
  10. String类 and StringBuffer类
  11. Javascript学习4 - 对象和数组
  12. NYOJ-914 Youth的最大化(贪心)
  13. Python入门学习(二)
  14. rn最新版测试
  15. Linux学习笔记8
  16. [AHOI2008] 紧急集合
  17. CentOS7日期时间设置方法以及时间基本概念介绍
  18. eclipse:刪除空行
  19. java.lang.NoSuchFieldError: No static field abc_ic_ab_back_mtrl_am_alpha of type I in class Landroid/support/v7/appcompat/R$drawable
  20. windows 10 下配置安装node.js

热门文章

  1. ansible shell 之运行后台程序
  2. 提升Python编程效率的几种方法
  3. [BJDCTF2020]Easy MD5
  4. JavaWeb之搭建自己的MVC框架(三)
  5. Sequence Models Week 3 Neural Machine Translation
  6. VC6.0 The value of ESP was not properly saved across a function call 错误解决方法
  7. mysql比较运算,逻辑运算,范围查询,模糊查询
  8. POJ 1850:Code 组合数学
  9. Java--类初始化
  10. 向mysql数据库中插入数据时显示“Duplicate entry '1′ for key ‘PRIMARY' ”错误