Skip to content

Commit 5168c32

Browse files
committed
word break solution
1 parent fee5c4e commit 5168c32

1 file changed

Lines changed: 51 additions & 0 deletions

File tree

word-break/JeonJe.java

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
import java.util.*;
2+
3+
// n = s.length(), m = wordDict.size(), L = 사전 단어의 최대 길이
4+
// TC: O(n * m * L)
5+
// SC: O(n)
6+
class Solution {
7+
public boolean wordBreak(String s, List<String> wordDict) {
8+
int n = s.length();
9+
10+
// dp[i] = 인덱스 i부터 시작하는 뒷부분을 사전 단어로 빈틈없이 쪼갤 수 있는가
11+
boolean[] dp = new boolean[n + 1];
12+
dp[n] = true;
13+
14+
// dp[i]는 자기보다 오른쪽의 dp[i + word.length()]를 참조하므로 뒤에서 앞으로 채운다
15+
for (int i = n - 1; i >= 0; i--) {
16+
for (String word : wordDict) {
17+
// startsWith(word, i)는 substring 없이 i번째부터 비교한다
18+
if (s.startsWith(word, i) && dp[i + word.length()]) {
19+
dp[i] = true;
20+
break;
21+
}
22+
}
23+
}
24+
25+
return dp[0];
26+
}
27+
}
28+
29+
// 첫 번째 풀이 — top-down 재귀 + 메모이제이션 (TC: O(n^2 * m), SC: O(n^2))
30+
// 남은 뒷부분을 문자열 그대로 메모 key로 써서 substring으로 새 문자열을 만들고 그 문자열을 n개까지 저장한다.
31+
//
32+
// public boolean wordBreak(String s, List<String> wordDict) {
33+
// return dfs(s, wordDict, new HashMap<>());
34+
// }
35+
//
36+
// private boolean dfs(String s, List<String> wordDict, Map<String, Boolean> memo) {
37+
// if (s.isEmpty()) return true;
38+
// if (memo.containsKey(s)) return memo.get(s);
39+
//
40+
// for (String word : wordDict) {
41+
// if (s.startsWith(word)) {
42+
// if (dfs(s.substring(word.length()), wordDict, memo)) {
43+
// memo.put(s, true);
44+
// return true;
45+
// }
46+
// }
47+
// }
48+
//
49+
// memo.put(s, false);
50+
// return false;
51+
// }

0 commit comments

Comments
 (0)