-
Notifications
You must be signed in to change notification settings - Fork 119
/
Copy pathWord Break.js
54 lines (43 loc) · 1.24 KB
/
Word Break.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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
// Runtime: 72 ms (Top 92.39%) | Memory: 42.9 MB (Top 90.15%)
/**
* @param {string} s
* @param {string[]} wordDict
* @return {boolean}
*/
var wordBreak = function(s, wordDict) {
var dp = new Array(s.length + 1).fill(false);
dp[s.length] = true;
for (var i = s.length - 1; i >= 0; i--) {
for (const word of wordDict) {
if ((i + word.length) <= s.length
&& s.substring(i, i + word.length) === word) {
dp[i] = dp[i + word.length];
}
if(dp[i]) break;
}
}
return dp[0];
};
// naive approach, take each word from the set and check if they match
/// O(n ^ 2 * m)
// considering m as the dictionary size
/*
var dict = new Set();
for (const word of wordDict) {
dict.add(word);
}
return canSegment(s, dict, 0);
function canSegment (str, dict, index) {
if (index >= str.length) return true;
var success = false;
for (const word of dict.values()) {
if ((index + word.length) <= str.length) {
var substring = str.substring(index, index + word.length);
if (dict.has(substring)) {
success = success | canSegment(str, dict, index + word.length);
}
}
}
return success;
}
*/