Skip to content

Commit aaeb0b1

Browse files
committed
Word Break solution
1 parent 2c6c1d7 commit aaeb0b1

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

word-break/clara-shin.js

+34
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
/**
2+
* 문자열 s가 주어진 단어 사전 wordDict의 단어들로 분리될 수 있는지 확인하는 문제
3+
* 다이나믹 프로그래밍(DP)
4+
* 시간 복잡도: O(n * k) (k: 최대 단어 길이)
5+
* 공간 복잡도: O(n) (DP 배열 + 단어 집합)
6+
*/
7+
8+
/**
9+
* @param {string} s
10+
* @param {string[]} wordDict
11+
* @return {boolean}
12+
*/
13+
var wordBreak = function (s, wordDict) {
14+
const n = s.length;
15+
const dp = new Array(n + 1).fill(false); // DP 배열 초기화
16+
dp[0] = true; // 빈 문자열은 항상 분리 가능
17+
18+
const wordSet = new Set(wordDict); // 단어 사전을 Set으로 변환: 검색시간 O(1)
19+
20+
const maxWordLength = Math.max(...wordDict.map((word) => word.length)); // 단어의 최대 길이 찾기
21+
22+
for (let i = 0; i <= n; i++) {
23+
// 가능한 단어 길이만 검사
24+
for (let j = Math.max(0, i - maxWordLength); j < i; j++) {
25+
if (dp[j] && wordSet.has(s.substring(j, i))) {
26+
// dp[j]가 true이고, j부터 i까지의 부분 문자열이 단어 사전에 존재하는 경우
27+
dp[i] = true;
28+
break;
29+
}
30+
}
31+
}
32+
33+
return dp[n];
34+
};

0 commit comments

Comments
 (0)