forked from jyxia/LeetCode-JavaScript
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path139-wordBreak.js
40 lines (37 loc) · 1.15 KB
/
139-wordBreak.js
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
/**
* @param {string} s
* @param {set<string>} wordDict
* Note: wordDict is a Set object, see:
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set
* @return {boolean}
*/
// recursion, not accepted, time exceeds limits. O(N^2)
var wordBreak = function(s, wordDict) {
return helper(s, wordDict, 0);
};
var helper = function(s, wordDict, start) {
if (start === s.length) return true;
// also let ... of is an ES6 feature
for (var word of wordDict) {
var wLength = word.length;
if (s.substring(start, start + wLength) === word) {
if (helper(s, wordDict, start + wLength)) return true;
}
}
return false;
};
// Dynamic, accepted
var wordBreak = function(s, wordDict) {
var canBreak = [true];
for (var i = 0; i < s.length; i++) {
if (!canBreak[i]) continue;
for (var word of wordDict) {
var wLength = word.length;
if (canBreak[i + wLength]) continue;
if (s.substring(i, i + wLength) === word) {
canBreak[i + wLength] = true;
}
}
}
return canBreak[s.length] ? true : false;
};