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