Skip to content

Commit fd8d099

Browse files
committed
wordBreak solution
1 parent fc16417 commit fd8d099

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

word-break/moonjonghoo.js

+31
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
/**
2+
* @param {string} s
3+
* @param {string[]} wordDict
4+
* @return {boolean}
5+
*/
6+
var wordBreak = function (s, wordDict) {
7+
const memo = new Map(); // 실패/성공 여부 기억
8+
const wordSet = new Set(wordDict); // lookup 최적화
9+
10+
function canBreak(sub) {
11+
if (sub === "") return true;
12+
13+
if (memo.has(sub)) return memo.get(sub);
14+
15+
for (let i = 1; i <= sub.length; i++) {
16+
const prefix = sub.slice(0, i);
17+
if (wordSet.has(prefix)) {
18+
const suffix = sub.slice(i);
19+
if (canBreak(suffix)) {
20+
memo.set(sub, true);
21+
return true;
22+
}
23+
}
24+
}
25+
26+
memo.set(sub, false); // 실패한 경우도 기억
27+
return false;
28+
}
29+
30+
return canBreak(s);
31+
};

0 commit comments

Comments
 (0)