File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ # 7기 풀이
2+ # 시간 복잡도: 시간복잡도: O(n * m)
3+ # - n은 s의 길이, m은 wordDict의 평균 단어 길이
4+ # - 각 인덱스마다 wordDict를 순회하므로
5+ # 공간 복잡도: 공간복잡도: O(n)
6+ # - memo에 최대 n개의 인덱스를 저장
7+ class Solution :
8+ def wordBreak (self , s : str , wordDict : List [str ]) -> bool :
9+ memo = set ()
10+
11+ def dfs (i ):
12+ if i == len (s ):
13+ # i가 s의 길이가 되면 모든 탐색이 성공으로 끝났기 때문에
14+ # True로 반환
15+ return True
16+
17+ memo .add (i ) # 해당 인덱스에 대해서는 방문을 했기 때문에 memo
18+ for word in wordDict :
19+ if i + len (word ) in memo :
20+ # i + len(word)가 memoization해둔 인덱스라면 이미 성공한 케이스므로 통과
21+ continue
22+
23+ if i + len (word ) > len (s ):
24+ # i + len(word)가 len(s)보다 크면 탐색을 더이상 할 수 없으므로 continue
25+ continue
26+
27+ # 아직 방문을 하지 않은 index라면 단어를 slice하여 실제로 wordDict에 있는지 확인
28+ if s [i :i + len (word )] in wordDict :
29+ # 다음 인덱스 i + len(word)로 dfs 탐색
30+ check = dfs (i + len (word ))
31+ if check :
32+ # 모든게 성공되었을 땐 True 반환
33+ return True
34+
35+ return False
36+
37+ return dfs (0 )
You can’t perform that action at this time.
0 commit comments