Skip to content

Commit 82dc4f2

Browse files
committed
Add word-break solution
1 parent cfb842c commit 82dc4f2

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed

word-break/Jeehay28.js

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
/**
2+
* @param {string} s
3+
* @param {string[]} wordDict
4+
* @return {boolean}
5+
*/
6+
7+
// Time Complexity: O(n * w * m)
8+
// - n is the length of the string s.
9+
// - w is the number of words in the dictionary wordDict.
10+
// - m is the average length of words in wordDict.
11+
12+
// Space Complexity: O(n)
13+
// - The dp array of size n + 1 is the primary contributor to space usage, where n is the length of the string s.
14+
var wordBreak = function (s, wordDict) {
15+
dp = new Array(s.length + 1).fill(false);
16+
dp[0] = true;
17+
18+
// O(n)
19+
for (let i = 1; i <= s.length; i++) {
20+
// O(w)
21+
for (word of wordDict) {
22+
if (i >= word.length && s.slice(i - word.length, i) === word) {
23+
// s.slice(i - word.length, i), the slicing operation takes O(m), where m is the length of the word being checked
24+
dp[i] = dp[i - word.length];
25+
}
26+
27+
if (dp[i]) {
28+
break;
29+
}
30+
}
31+
}
32+
33+
return dp[s.length];
34+
};
35+
36+

0 commit comments

Comments
 (0)