Skip to content

Commit aeda377

Browse files
committed
0139-word-break
1 parent 21654f1 commit aeda377

1 file changed

Lines changed: 39 additions & 0 deletions

File tree

word-break/dahyeong-yun.java

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
/**
2+
* n: 문자열 s의 길이, m: wordDict 단어 수, k: 단어의 평균 길이
3+
* - TC: O(n * m * k) -> n개 인덱스 방문 × m개 단어 순회 × k 길이 문자열 비교
4+
* - SC: O(n) -> 메모이제이션 배열 및 재귀 스택 깊이 O(n)
5+
*/
6+
class Solution {
7+
String s;
8+
int len = 0;
9+
boolean[] imposible;
10+
List<String> wordDict;
11+
12+
public boolean wordBreak(String s, List<String> wordDict) {
13+
this.s = s;
14+
this.len = s.length();
15+
this.imposible = new boolean[len];
16+
this.wordDict = wordDict;
17+
return dfs(0);
18+
}
19+
20+
public boolean dfs(int index) {
21+
if(index == len) {
22+
return true;
23+
}
24+
25+
if(imposible[index]) return false;
26+
27+
for(String word : wordDict) {
28+
int wordLength = word.length();
29+
if(s.startsWith(word, index)) {
30+
if(len >= index + wordLength) {
31+
if(dfs(index + wordLength)) return true;
32+
}
33+
}
34+
}
35+
36+
imposible[index] = true;
37+
return false;
38+
}
39+
}

0 commit comments

Comments
 (0)