This repository has been archived by the owner on Aug 23, 2023. It is now read-only.
/
WordBreakProblem.cs
63 lines (53 loc) · 1.6 KB
/
WordBreakProblem.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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CS.Problems.DynamicProgramming
{
/// <summary>
/// Problem details below
/// http://www.geeksforgeeks.org/dynamic-programming-set-32-word-break-problem/
/// </summary>
public class WordBreakProblem
{
public static bool CanBreak(HashSet<string> dictionary, string sentence)
{
return CanBreak(dictionary, sentence, sentence.Length, new Dictionary<int, bool>());
}
private static bool CanBreak(HashSet<string> dictionary,
string sentence, int charIndex, Dictionary<int, bool> cache)
{
if (charIndex == 0)
{
return true;
}
if (cache.ContainsKey(charIndex))
{
return cache[charIndex];
}
var result = false;
for (int i = 0; i < charIndex; i++)
{
if (CanBreak(dictionary, sentence, i, cache))
{
if (IsMatch(dictionary, sentence.Substring(i, charIndex - i)))
{
result = true;
break;
}
}
}
cache.Add(charIndex, result);
return result;
}
private static bool IsMatch(HashSet<string> dictionary, string searchWord)
{
if (dictionary.Contains(searchWord))
{
return true;
}
return false;
}
}
}