generated from eyamenko/dotnet-template-repository
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Problem27.cs
58 lines (50 loc) · 1.7 KB
/
Problem27.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
namespace LeetCode;
/// <summary>
/// <see href="https://leetcode.com/problems/word-break/">Word Break</see>.
/// </summary>
public static class Problem27
{
/// <summary>
/// Given a string s and a dictionary of strings wordDict, return true if s can be segmented into a space-separated sequence of one or more dictionary words.
/// Note that the same word in the dictionary may be reused multiple times in the segmentation.
/// Time complexity: O(s^2 + n).
/// Space complexity: O(s + n).
/// </summary>
/// <param name="s">String to traverse.</param>
/// <param name="wordDict">Word dictionary.</param>
/// <returns>True, if the input string can be segmented.</returns>
public static bool WordBreak(string s, IList<string> wordDict)
{
var wordDictSet = new HashSet<string>(wordDict.Count);
for (var i = 0; i < wordDict.Count; i++)
{
#pragma warning disable IDE0058
wordDictSet.Add(wordDict[i]);
#pragma warning restore IDE0058
}
return Traverse(s, 0, new bool[s.Length], wordDictSet);
}
private static bool Traverse(string s, int i, bool[] wordBreaks, ISet<string> wordDictSet)
{
if (i >= s.Length)
{
return true;
}
if (wordBreaks[i])
{
return false;
}
for (int left = i, right = Math.Min(left + 20, s.Length); left < right; left++)
{
if (wordDictSet.Contains(s[i..(left + 1)]))
{
wordBreaks[i] = true;
if (Traverse(s, left + 1, wordBreaks, wordDictSet))
{
return true;
}
}
}
return false;
}
}