/
DailyCodingProblem10062018.cs
86 lines (80 loc) · 1.75 KB
/
DailyCodingProblem10062018.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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DailyCodingProblem
{
class DailyCodingProblem10062018
{
private SimpleTrie trie = null;
public DailyCodingProblem10062018()
{
string[] words = { "mantel",
"piece",
"shelf",
"air",
"airborne",
"born",
"this",
"is",
"a",
"add",
"addon",
"on",
"quick",
"brown",
"the",
"fox",
"bed",
"bath",
"bedbath",
"beyond",
"quicker",
"aftereffect",
"afternoon",
"afterthought",
"airbag",
"anybody",
"how",
"any",
"anyhow",
"anywho",
"ever",
"however"
};
trie = new SimpleTrie();
foreach (string word in words) trie.AddWord(word);
}
public void PrintMinWords(string input)
{
PrintMinWords("", 0, input);
}
private bool PrintMinWords(string str, int index, string input)
{
//Base case
if (String.IsNullOrEmpty(input)) return false;
if (index >= input.Length)
{
PrintWords(str);
return true;
}
//Induction, backtracking
int last = input.Length - 1;
while (last >= index)
{
string substr = input.Substring(index, last - index + 1);
if (trie.IsWordPresent(substr) && PrintMinWords(str + "@" + substr, last + 1, input)) return true;
last--;
}
return false;
}
private void PrintWords(string str)
{
if (String.IsNullOrEmpty(str)) return;
string[] parts = str.Split(new string[] { "@" }, StringSplitOptions.RemoveEmptyEntries);
foreach (string part in parts) Console.Write("{0} ", part);
Console.WriteLine();
}
}
}