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