Skip to content

Commit fd4b0ea

Browse files
authored
Create LongestStringChain.java
1 parent be0b20c commit fd4b0ea

File tree

1 file changed

+59
-0
lines changed

1 file changed

+59
-0
lines changed

LongestStringChain.java

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
class Solution {
2+
3+
public int longestStrChain(String[] words) {
4+
5+
List<List<Integer>> paths = buildGraph(words);
6+
7+
int[] scores = new int[words.length];
8+
int maximumLength = 0;
9+
10+
for(int i = 0; i < words.length; i++) {
11+
maximumLength = Math.max(maximumLength, longest(i, scores, paths));
12+
}
13+
14+
return maximumLength;
15+
16+
}
17+
18+
private List<List<Integer>> buildGraph(String[] words) {
19+
List<List<Integer>> paths = new ArrayList<>(words.length);
20+
Map<String, Integer> wordIdx = new HashMap<>();
21+
22+
for (int i = 0; i < words.length; i++) {
23+
paths.add(new LinkedList<>());
24+
wordIdx.put(words[i], i);
25+
}
26+
27+
for (int i = 0; i < words.length; i++) {
28+
String word = words[i];
29+
for(int j = 0; j < word.length(); j++) {
30+
String possible = word.substring(0, j) + word.substring(j + 1);
31+
32+
if (!wordIdx.containsKey(possible)) continue;
33+
34+
int possibleIdx = wordIdx.get(possible);
35+
36+
List<Integer> possiblePaths = paths.get(possibleIdx);
37+
possiblePaths.add(i);
38+
paths.set(possibleIdx, possiblePaths);
39+
}
40+
}
41+
42+
return paths;
43+
}
44+
45+
private int longest(int v, int[] scores, List<List<Integer>> paths) {
46+
if (scores[v] > 0) return scores[v];
47+
48+
int longestPath = 1;
49+
50+
for(Integer child: paths.get(v)) {
51+
longestPath = Math.max(longestPath, longest(child, scores, paths) + 1);
52+
}
53+
54+
scores[v] = longestPath;
55+
56+
return longestPath;
57+
}
58+
59+
}

0 commit comments

Comments
 (0)