-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path0472-ConcatenatedWords.cs
41 lines (35 loc) · 1.14 KB
/
0472-ConcatenatedWords.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
//-----------------------------------------------------------------------------
// Runtime: 576ms
// Memory Usage: 48.9 MB
// Link: https://leetcode.com/submissions/detail/365358654/
//-----------------------------------------------------------------------------
using System.Collections.Generic;
namespace LeetCode
{
public class _0472_ConcatenatedWords
{
public IList<string> FindAllConcatenatedWordsInADict(string[] words)
{
var set = new HashSet<string>(words);
var result = new List<string>();
foreach (var word in words)
{
set.Remove(word);
if (DFS(word, set))
result.Add(word);
set.Add(word);
}
return result;
}
private bool DFS(string word, HashSet<string> set)
{
if (set.Contains(word)) return true;
for (int i = word.Length - 1; i > 0; i--)
{
var str = word.Substring(0, i);
if (set.Contains(str) && DFS(word.Substring(i), set)) return true;
}
return false;
}
}
}