[139] 单词拆分

This commit is contained in:
Wen 2023-07-20 21:51:13 +08:00
parent d99f003c20
commit 7cd3bcd44e
1 changed files with 30 additions and 0 deletions

View File

@ -0,0 +1,30 @@
/*
* @lc app=leetcode.cn id=139 lang=javascript
*
* [139] 单词拆分
*/
// @lc code=start
/**
* @param {string} s
* @param {string[]} wordDict
* @return {boolean}
*/
const wordBreak = (s, wordDict) => {
const wordSet = new Set(wordDict);
const len = s.length;
const dp = new Array(len + 1).fill(false);
dp[0] = true;
for (let i = 1; i <= len + 1; i++) {
for (let j = 0; j < i; j++) {
if (dp[j] && wordSet.has(s.substring(j, i))) {
dp[i] = true;
break;
}
}
}
return dp[len];
};
console.log(wordBreak('leetcode', ['leet', 'code']));
// @lc code=end