
Sponsored
Sponsored
This approach involves sorting the array of words based on their lengths, which helps in easily recognizing the potential predecessors. Then, utilize a dynamic programming technique to build up the solution. For each word, check all words that are predecessors and update the maximum chain length accordingly.
Time Complexity: O(n^2 * l), where n is the number of words and l is the average length of each word. The sorting step contributes O(n log n) but checking each predecessor might happen in O(n^2). The maximum comparison takes O(l) time.
Space Complexity: O(n) for the dp array.
1using System;
2using System.Collections.Generic;
3
4public class Solution {
5 public int LongestStrChain(string[] words) {
6 Array.Sort(words, (a, b) => a.Length.CompareTo(b.Length));
7 Dictionary<string, int> dp = new Dictionary<string, int>();
8 int maxLen = 1;
9
10 foreach (string word in words) {
11 dp[word] = 1;
12 for (int i = 0; i < word.Length; i++) {
13 string prev = word.Substring(0, i) + word.Substring(i + 1);
14 if (dp.ContainsKey(prev)) {
15 dp[word] = Math.Max(dp[word], dp[prev] + 1);
16 }
17 }
18 maxLen = Math.Max(maxLen, dp[word]);
19 }
20
21 return maxLen;
22 }
23
24 public static void Main(string[] args) {
25 Solution solution = new Solution();
26 string[] words = new [] {"a", "b", "ba", "bca", "bda", "bdca"};
27 Console.WriteLine(solution.LongestStrChain(words));
28 }
29}The C# solution implements the dynamic programming approach with a Dictionary to store maximum chain lengths. The method iteratively calculates chain lengths by examining subsets of each word as it is sorted by length.
This approach models the words as nodes in a graph and links words via edges if one is a predecessor of the other. The goal is to find the longest path in this directed acyclic graph (DAG), which represents the longest word chain.
Time Complexity: O(n^2 * l), where n is the number of words and l is the average word length as this is similar to a dynamic programming solution.
Space Complexity: O(n) for the dynamic programming path length array.
1using System.Collections.Generic;
public class Solution {
public int LongestStrChain(string[] words) {
Array.Sort(words, (a, b) => a.Length.CompareTo(b.Length));
Dictionary<string, int> dp = new Dictionary<string, int>();
int maxLen = 1;
foreach (string word in words) {
dp[word] = 1;
for (int i = 0; i < word.Length; i++) {
string prev = word.Substring(0, i) + word.Substring(i + 1);
if (dp.ContainsKey(prev)) {
dp[word] = Math.Max(dp[word], dp[prev] + 1);
}
}
maxLen = Math.Max(maxLen, dp[word]);
}
return maxLen;
}
public static void Main(string[] args) {
Solution solution = new Solution();
string[] words = new [] {"a", "b", "ba", "bca", "bda", "bdca"};
Console.WriteLine(solution.LongestStrChain(words));
}
}Graph vertices in this C# solution represent individual words, and directed edges indicate a predecessor relationship. Finding the longest path effectively implies the chain solution.