Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit 77bcf76

Browse files
author
eunhwa99
committedJan 6, 2025·
word break
1 parent 3228d99 commit 77bcf76

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed
 

‎word-break/eunhwa99.java

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
import java.util.List;
2+
3+
4+
// 풀이
5+
// dfs + memo
6+
// memo[i] = true/false : i 인덱스에서 시작해서 wordDict에 존재하는 모든 부분문자열 찾을 수 있는 경로가 있는지 유무
7+
//시간 복잡도: O(n*n) = start~end(재귀) + start~end(반복문)
8+
// 공간 복잡도: O(n) - 재귀 깊이
9+
10+
class Solution {
11+
12+
public boolean wordBreak(String s, List<String> wordDict) {
13+
return dfs(0, s.length(), s, wordDict, new Boolean[s.length()]);
14+
15+
}
16+
public boolean dfs(int start, int len, String s, List<String> wordDict, Boolean[] memo){
17+
if(start==len){
18+
return true;
19+
}
20+
21+
if(memo[start]!=null) return memo[start];
22+
23+
for(int end=start+1; end<=len;end++){
24+
if(wordDict.contains(s.substring(start, end))){
25+
if(dfs(end, len, s, wordDict, memo)){
26+
memo[start] = true;
27+
return true;
28+
}
29+
}
30+
}
31+
32+
memo[start]=false;
33+
return false;
34+
35+
}
36+
}

0 commit comments

Comments
 (0)
Please sign in to comment.