From 1ce40c1dc6890f699637790183485a7ce7426024 Mon Sep 17 00:00:00 2001 From: Paik Date: Mon, 6 Jan 2025 20:03:48 +0900 Subject: [PATCH] 139. Word Break --- word-break/gwbaik9717.js | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 word-break/gwbaik9717.js diff --git a/word-break/gwbaik9717.js b/word-break/gwbaik9717.js new file mode 100644 index 000000000..ca7754f75 --- /dev/null +++ b/word-break/gwbaik9717.js @@ -0,0 +1,25 @@ +// n: len(s), m: len(wordDict) +// Time complexity: O(n^2*m) +// Space complexity: O(n) + +/** + * @param {string} s + * @param {string[]} wordDict + * @return {boolean} + */ +var wordBreak = function (s, wordDict) { + const dp = Array.from({ length: s.length + 1 }, () => false); + dp[0] = true; + + for (let i = 1; i <= s.length; i++) { + for (const word of wordDict) { + const sliced = s.slice(i - word.length, i); + + if (word === sliced && !dp[i]) { + dp[i] = dp[i - word.length]; + } + } + } + + return dp.at(-1); +};