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
| class Solution { public int longestStrChain(String[] words) { Map<String, Integer> memo = new HashMap<>(); Set<String> wordSet = new HashSet<>(); Collections.addAll(wordSet, words); int ans = 0; for (String word : words) { ans = Math.max(ans, helper(word, memo, wordSet)); } return ans; }
private int helper(String word, Map<String, Integer> memo, Set<String> wordSet) { if (memo.containsKey(word)) { return memo.get(word); } StringBuilder currWord = new StringBuilder(word); int maxLength = 1; for (int i = 0; i < currWord.length(); i++) { currWord.deleteCharAt(i); String newWord = currWord.toString(); if (wordSet.contains(newWord)) { maxLength = Math.max(maxLength, helper(newWord, memo, wordSet) + 1); } currWord.insert(i, word.charAt(i)); } memo.put(word, maxLength); return maxLength; } }
|