|
| 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