1048. Longest String Chain
Last updated
Last updated
/**
* Time complexity : O(N *(log(N+L^2))). Where N be the number of words in
* the list and L be the maximum possible length of a word.
* Space complexity : O(N). We use a map to store the length of the longest
* sequence formed with each of the NN words as the end word.
*/
class Solution {
public int longestStrChain(String[] words) {
if(words == null || words.length < 2) {
return words == null? 0: words.length;
}
Arrays.sort(words, (a, b) -> a.length()-b.length());
Map<String, Integer> map = new HashMap();
int longest = 0;
for(String word: words) {
int currLongest = 0;
for(int i = 0; i < word.length(); i++) {
StringBuilder prevWordSb = new StringBuilder(word);
prevWordSb.deleteCharAt(i);
int prevLength = 1 + map.getOrDefault(prevWordSb.toString(), 0);
currLongest = Math.max(currLongest, prevLength);
}
map.put(word, currLongest);
longest = Math.max(longest, currLongest);
}
return longest;
}
}