-
Notifications
You must be signed in to change notification settings - Fork 120
/
Copy path0139-WordBreak.cs
49 lines (43 loc) · 1.49 KB
/
0139-WordBreak.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
//-----------------------------------------------------------------------------
// Runtime: 92ms
// Memory Usage: 24.4 MB
// Link: https://leetcode.com/submissions/detail/378107269/
//-----------------------------------------------------------------------------
using System;
using System.Collections.Generic;
namespace LeetCode
{
public class _0139_WordBreak
{
public bool WordBreak(string s, IList<string> wordDict)
{
int minLength = int.MaxValue, maxLength = int.MinValue;
var map = new HashSet<string>();
foreach (var item in wordDict)
{
map.Add(item);
maxLength = Math.Max(maxLength, item.Length);
minLength = Math.Min(minLength, item.Length);
}
var dp = new bool[s.Length];
var index = 0;
while (index < s.Length)
{
for (int length = minLength; index + length <= s.Length && length <= maxLength; length++)
if (map.Contains(s.Substring(index, length)))
dp[index + length - 1] = true;
var j = index;
var found = false;
while (j < s.Length)
if (dp[j++])
{
index = j;
found = true;
break;
}
if (!found) return false;
}
return dp[s.Length - 1];
}
}
}