Skip to content

Commit 256c5f2

Browse files
committed
word break solution
1 parent addfd6b commit 256c5f2

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed

word-break/byol-han.js

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
/**
2+
* https://leetcode.com/problems/word-break/
3+
* @param {string} s
4+
* @param {string[]} wordDict
5+
* @return {boolean}
6+
*/
7+
var wordBreak = function (s, wordDict) {
8+
const wordSet = new Set(wordDict);
9+
const dp = new Array(s.length + 1).fill(false);
10+
dp[0] = true; // 빈 문자열은 항상 true
11+
12+
for (let i = 1; i <= s.length; i++) {
13+
for (let j = 0; j < i; j++) {
14+
if (dp[j] && wordSet.has(s.substring(j, i))) {
15+
dp[i] = true;
16+
break;
17+
}
18+
}
19+
}
20+
21+
return dp[s.length];
22+
};
23+
24+
/*
25+
Set은 검색이 빠르다
26+
wordDict가 배열이면, includes()로 단어가 있는지 찾을 때 O(n) 시간이 걸림
27+
하지만 Set을 사용하면 has() 메서드로 단어가 있는지 O(1) 시간이 걸림
28+
이 차이는 s.length가 길거나 wordDict가 클수록 성능에 큰 영향
29+
*/

0 commit comments

Comments
 (0)