|
6 | 6 |
|
7 | 7 | // @lc code=start
|
8 | 8 | /**
|
9 |
| - * |
| 9 | + * 解法 1: 自顶向下 |
| 10 | + */ |
| 11 | +// function wordBreak(s: string, wordDict: string[]): boolean { |
| 12 | +// const dpTable = new Map() |
| 13 | +// function dp(s) { |
| 14 | +// if (s === '') return true |
| 15 | +// if (dpTable.has(s)) return dpTable.get(s) |
| 16 | +// for (let i = 0; i < wordDict.length; i++) { |
| 17 | +// let result = dp(s.substring(wordDict[i].length)) |
| 18 | +// dpTable.set(s.substring(wordDict[i].length), result) |
| 19 | +// if (s.substring(0, wordDict[i].length) === wordDict[i] && result) { |
| 20 | +// return true |
| 21 | +// } |
| 22 | +// } |
| 23 | +// return false |
| 24 | +// } |
| 25 | +// return dp(s) |
| 26 | +// }; |
| 27 | + |
| 28 | +/** |
| 29 | + * 解法 2: 自底向上 |
10 | 30 | */
|
11 | 31 | function wordBreak(s: string, wordDict: string[]): boolean {
|
12 |
| - const dpTable = new Map() |
13 |
| - function dp(s) { |
14 |
| - if (s === '') return true |
15 |
| - if (dpTable.has(s)) return dpTable.get(s) |
16 |
| - for (let i = 0; i < wordDict.length; i++) { |
17 |
| - let result = dp(s.substring(wordDict[i].length)) |
18 |
| - dpTable.set(s.substring(wordDict[i].length), result) |
19 |
| - if (s.substring(0, wordDict[i].length) === wordDict[i] && result) { |
20 |
| - return true |
| 32 | + |
| 33 | + // 空字符串,可以组合成 |
| 34 | + // const dp = [true] |
| 35 | + const dpMap = new Map() |
| 36 | + dpMap.set('', true) |
| 37 | + for (let i = 0; i < s.length; i++) { |
| 38 | + for (let j = 0; j < wordDict.length; j++) { |
| 39 | + if (dpMap.get(s.substring(0, i)) && s.substring(i, i + wordDict[j].length) === wordDict[j]) { |
| 40 | + dpMap.set(s.substring(0, i) + wordDict[j], true) |
| 41 | + // break |
21 | 42 | }
|
| 43 | + |
22 | 44 | }
|
23 |
| - return false |
24 | 45 | }
|
25 |
| - return dp(s) |
26 |
| -}; |
| 46 | + return !!dpMap.get(s) |
| 47 | +} |
| 48 | + |
27 | 49 | // @lc code=end
|
28 | 50 |
|
29 |
| -// console.log(wordBreak("leetcode", ["leet", "code"])) |
30 |
| -console.log(wordBreak("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaab", |
31 |
| - ["a", "aa", "aaa", "aaaa", "aaaaa", "aaaaaa", "aaaaaaa", "aaaaaaaa", "aaaaaaaaa", "aaaaaaaaaa"])) |
| 51 | +console.log(wordBreak("applepenapple", ["apple", "pen"])) |
| 52 | +// console.log(wordBreak("aab", |
| 53 | +// ["a", "aa", "aaa", "aaaa", "aaaaa", "aaaaaa", "aaaaaaa", "aaaaaaaa", "aaaaaaaaa", "aaaaaaaaaa"])) |
32 | 54 |
|
0 commit comments