|
| 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