Created
May 17, 2021 15:44
-
-
Save vrat28/11396562c11033219f41ca5eea55641f to your computer and use it in GitHub Desktop.
Longest String Chain (Bottom Up) Java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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