LeetCode 1048: Longest String Chain Solution
Master LeetCode problem 1048 (Longest String Chain), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
1048. Longest String Chain
Problem Explanation
Explanation:
To solve this problem, we can follow these steps:
- Sort the words based on their lengths.
- Initialize a HashMap to store the maximum chain length for each word.
- For each word in the sorted list:
- Calculate all possible predecessor words by removing one character at a time.
- Update the maximum chain length for the current word by finding the maximum of the chain lengths of its predecessors.
- Return the maximum chain length found in the HashMap.
Time Complexity: O(n * m^2), where n is the number of words and m is the average length of each word. Space Complexity: O(n)
:
Solution Code
class Solution {
public int longestStrChain(String[] words) {
Arrays.sort(words, Comparator.comparingInt(String::length));
Map<String, Integer> chainLengths = new HashMap<>();
int maxChainLength = 1;
for (String word : words) {
int currMax = 1;
for (int i = 0; i < word.length(); i++) {
StringBuilder predecessor = new StringBuilder(word);
predecessor.deleteCharAt(i);
currMax = Math.max(currMax, chainLengths.getOrDefault(predecessor.toString(), 0) + 1);
}
chainLengths.put(word, currMax);
maxChainLength = Math.max(maxChainLength, currMax);
}
return maxChainLength;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 1048 (Longest String Chain)?
This page provides optimized solutions for LeetCode problem 1048 (Longest String Chain) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 1048 (Longest String Chain)?
The time complexity for LeetCode 1048 (Longest String Chain) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 1048 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1048 in Java, C++, or Python.