Skip to content

Commit 5cb3615

Browse files
committed
Feat: 139. Word Break
1 parent f89c4c6 commit 5cb3615

File tree

1 file changed

+23
-0
lines changed

1 file changed

+23
-0
lines changed

word-break/HC-kang.ts

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
/**
2+
* https://leetcode.com/problems/word-break
3+
* T.C. O(s^2)
4+
* S.C. O(s + w)
5+
*/
6+
function wordBreak(s: string, wordDict: string[]): boolean {
7+
const wordSet = new Set(wordDict);
8+
9+
const dp = new Array(s.length + 1).fill(false);
10+
dp[0] = true;
11+
12+
for (let i = 1; i <= s.length; i++) {
13+
for (let j = 0; j < i; j++) {
14+
if (!dp[j]) continue;
15+
if (j-i > 20) break;
16+
if (wordSet.has(s.slice(j, i))) {
17+
dp[i] = true;
18+
break;
19+
}
20+
}
21+
}
22+
return dp[s.length];
23+
}

0 commit comments

Comments
 (0)