Skip to content

Commit 1ce40c1

Browse files
committed
139. Word Break
1 parent 1e90ed0 commit 1ce40c1

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed

word-break/gwbaik9717.js

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
// n: len(s), m: len(wordDict)
2+
// Time complexity: O(n^2*m)
3+
// Space complexity: O(n)
4+
5+
/**
6+
* @param {string} s
7+
* @param {string[]} wordDict
8+
* @return {boolean}
9+
*/
10+
var wordBreak = function (s, wordDict) {
11+
const dp = Array.from({ length: s.length + 1 }, () => false);
12+
dp[0] = true;
13+
14+
for (let i = 1; i <= s.length; i++) {
15+
for (const word of wordDict) {
16+
const sliced = s.slice(i - word.length, i);
17+
18+
if (word === sliced && !dp[i]) {
19+
dp[i] = dp[i - word.length];
20+
}
21+
}
22+
}
23+
24+
return dp.at(-1);
25+
};

0 commit comments

Comments
 (0)