LC.P1048[最长字符串链]

方法一:动态规划+记忆化搜索

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {
Map<String, Integer> map = new HashMap<>();

public int longestStrChain(String[] words) {
for (String word : words) map.put(word, 0);
int ans = 0;
for (String s : map.keySet()) {
ans = Math.max(ans, dfs(s));
}
return ans;
}

private int dfs(String s) {
int ans = map.get(s);
if (ans > 0) return ans;
for (int i = 0; i < s.length(); ++i) {
String t = s.substring(0, i) + s.substring(i + 1);
if (map.containsKey(t)) ans = Math.max(ans, dfs(t));
}
map.put(s, ans + 1);
return ans + 1;
}
}

方法二:1:1翻译成递推

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution {
public int longestStrChain(String[] words) {
int ans = 0;
Map<String, Integer> map = new HashMap<>();
Arrays.sort(words, (a, b) -> a.length() - b.length());
for (String word : words) {
int res = 0;
for (int i = 0; i < word.length(); ++i) {
String t = word.substring(0, i) + word.substring(i + 1);
res = Math.max(res, map.getOrDefault(t, 0));
}
map.put(word, res + 1);
ans = Math.max(ans, res + 1);
}
return ans;
}
}