Skip to content

Instantly share code, notes, and snippets.

@vrat28
Created May 17, 2021 15:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vrat28/11396562c11033219f41ca5eea55641f to your computer and use it in GitHub Desktop.
Save vrat28/11396562c11033219f41ca5eea55641f to your computer and use it in GitHub Desktop.
Longest String Chain (Bottom Up) Java
class Solution {
public int longestStrChain(String[] words) {
Map<String, Integer> dp = new HashMap<>();
// Sorting the list in terms of the word length.
Arrays.sort(words, (a, b) -> a.length() - b.length());
int longestWordSequenceLength = 1;
for (String word : words) {
int presentLength = 1;
// Find all possible predecessors for the current word by removing one letter at a time.
for (int i = 0; i < word.length(); i++) {
StringBuilder temp = new StringBuilder(word);
temp.deleteCharAt(i);
String predecessor = temp.toString();
int previousLength = dp.getOrDefault(predecessor, 0);
presentLength = Math.max(presentLength, previousLength + 1);
}
dp.put(word, presentLength);
longestWordSequenceLength = Math.max(longestWordSequenceLength, presentLength);
}
return longestWordSequenceLength;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment