-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution1048.cs
49 lines (39 loc) · 1.16 KB
/
Solution1048.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
using System.Text;
using LeetCode.DataStructures;
namespace LeetCode.Solutions;
public class Solution1048
{
/// <summary>
/// 1048. Longest String Chain - Medium
/// <a href="https://leetcode.com/problems/longest-string-chain</a>
/// </summary>
public int LongestStrChain(string[] words)
{
var wordSet = new HashSet<string>(words);
var dp = new Dictionary<string, int>();
var maxChainLength = 1;
foreach (var word in words)
{
maxChainLength = Math.Max(maxChainLength, DFS(word, wordSet, dp));
}
return maxChainLength;
}
private int DFS(string word, HashSet<string> wordSet, Dictionary<string, int> dp)
{
if (dp.ContainsKey(word))
{
return dp[word];
}
var maxChainLength = 1;
for (var i = 0; i < word.Length; i++)
{
var nextWord = word.Remove(i, 1);
if (wordSet.Contains(nextWord))
{
maxChainLength = Math.Max(maxChainLength, 1 + DFS(nextWord, wordSet, dp));
}
}
dp[word] = maxChainLength;
return maxChainLength;
}
}