[LC] 1048. Longest String Chain
2024-09-07 07:31:23
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:
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;
}
}
最新文章
- [LeetCode] Reverse Words in a String II 翻转字符串中的单词之二
- Linux新手扫盲(转载)
- 【51Nod 1616】【算法马拉松 19B】最小集合
- 详细了解HTML标签内容模型
- 【UWP】UI适配整理
- Android onTouchEvent, onClick及onLongClick的调用机制
- Python笔记(一)
- Jquery图片放大镜
- poj 1328 Radar Installation(贪心)
- String类 and StringBuffer类
- Javascript学习4 - 对象和数组
- NYOJ-914 Youth的最大化(贪心)
- Python入门学习(二)
- rn最新版测试
- Linux学习笔记8
- [AHOI2008] 紧急集合
- CentOS7日期时间设置方法以及时间基本概念介绍
- eclipse:刪除空行
- java.lang.NoSuchFieldError: No static field abc_ic_ab_back_mtrl_am_alpha of type I in class Landroid/support/v7/appcompat/R$drawable
- windows 10 下配置安装node.js
热门文章
- ansible shell 之运行后台程序
- 提升Python编程效率的几种方法
- [BJDCTF2020]Easy MD5
- JavaWeb之搭建自己的MVC框架(三)
- Sequence Models Week 3 Neural Machine Translation
- VC6.0 The value of ESP was not properly saved across a function call 错误解决方法
- mysql比较运算,逻辑运算,范围查询,模糊查询
- POJ 1850:Code 组合数学
- Java--类初始化
- 向mysql数据库中插入数据时显示“Duplicate entry '1′ for key ‘PRIMARY' ”错误