Skip to content

Commit 162a26b

Browse files
authored
Update Longest String Chain.java
1 parent e2c2b23 commit 162a26b

File tree

1 file changed

+27
-25
lines changed

1 file changed

+27
-25
lines changed

Medium/Longest String Chain.java

Lines changed: 27 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -1,29 +1,31 @@
11
class Solution {
2-
public int longestStrChain(String[] words) {
3-
Map<String, Integer> dp = new HashMap<>();
4-
Set<String> wordSet = Arrays.stream(words).collect(Collectors.toSet());
5-
int maxLength = 0;
6-
for (String word : words) {
7-
maxLength = Math.max(maxLength, dfs(wordSet, dp, word));
2+
public int longestStrChain(String[] words) {
3+
Set<String> wordSet = Arrays.stream(words)
4+
.collect(Collectors.toSet());
5+
Map<String, Integer> memo = new HashMap<>();
6+
int result = 0;
7+
for (String word : words) {
8+
result = Math.max(result, dfs(wordSet, memo, word));
9+
}
10+
return result;
811
}
9-
return maxLength;
10-
}
11-
12-
private int dfs(Set<String> wordSet, Map<String, Integer> dp, String currWord) {
13-
if (dp.containsKey(currWord)) {
14-
return dp.get(currWord);
12+
13+
private int dfs(Set<String> wordSet, Map<String, Integer> memo, String word) {
14+
if (memo.containsKey(word)) {
15+
return memo.get(word);
16+
}
17+
int maxLength = 1;
18+
StringBuilder sb = new StringBuilder(word);
19+
for (int i = 0; i < word.length(); i++) {
20+
sb.deleteCharAt(i);
21+
String newWord = sb.toString();
22+
if (wordSet.contains(newWord)) {
23+
int currLength = 1 + dfs(wordSet, memo, newWord);
24+
maxLength = Math.max(maxLength, currLength);
25+
}
26+
sb.insert(i, word.charAt(i));
27+
}
28+
memo.put(word, maxLength);
29+
return maxLength;
1530
}
16-
int maxLength = 1;
17-
StringBuilder sb = new StringBuilder(currWord);
18-
for (int i = 0; i < currWord.length(); i++) {
19-
sb.deleteCharAt(i);
20-
String newWord = sb.toString();
21-
if (wordSet.contains(newWord)) {
22-
maxLength = Math.max(maxLength, 1 + dfs(wordSet, dp, newWord));
23-
}
24-
sb.insert(i, currWord.charAt(i));
25-
}
26-
dp.put(currWord, maxLength);
27-
return dp.get(currWord);
28-
}
2931
}

0 commit comments

Comments
 (0)