Skip to content

Commit 3f79d02

Browse files
committed
solve: word break
1 parent 3ae37aa commit 3f79d02

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed

β€Žword-break/tolluset.tsβ€Ž

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
/*
2+
* TC: O(n^2)
3+
* SC: O(n)
4+
* */
5+
function wordBreak(s: string, wordDict: string[]): boolean {
6+
const n = s.length;
7+
const wordSet = new Set(wordDict);
8+
const dp = Array(n + 1).fill(false);
9+
10+
dp[0] = true;
11+
12+
for (let i = 1; i <= n; i++) {
13+
for (let j = 0; j < i; j++) {
14+
if (dp[j] && wordSet.has(s.slice(j, i))) {
15+
dp[i] = true;
16+
break;
17+
}
18+
}
19+
}
20+
21+
return dp[n];
22+
}
23+
24+
const tc1 = wordBreak("leetcode", ["leet", "code"]); // true
25+
console.info("πŸš€ : tolluset.ts:17: tc1=", tc1);
26+
27+
const tc2 = wordBreak("applepenapple", ["apple", "pen"]); // true
28+
console.info("πŸš€ : tolluset.ts:20: tc2=", tc2);
29+
30+
const tc3 = wordBreak("catsandog", ["cats", "dog", "sand", "and", "cat"]); // false
31+
console.info("πŸš€ : tolluset.ts:23: tc3=", tc3);
32+
33+
const tc4 = wordBreak("cars", ["car", "ca", "rs"]); // true
34+
console.info("πŸš€ : tolluset.ts:27: tc4=", tc4);
35+
36+
const tc5 = wordBreak("aaaaaaa", ["aaaa", "aaa"]); // true
37+
console.info("πŸš€ : tolluset.ts:32: tc5=", tc5);
38+
39+
const tc6 = wordBreak("cbca", ["bc", "ca"]); // false
40+
console.info("πŸš€ : tolluset.ts:43: tc6=", tc6);

0 commit comments

Comments
Β (0)