File tree Expand file tree Collapse file tree 1 file changed +37
-0
lines changed Expand file tree Collapse file tree 1 file changed +37
-0
lines changed Original file line number Diff line number Diff line change 1+ """
2+ 풀이 :
3+ dp 배열은 s에서 길이n까지의 문자열이 word를 통해 만들어질 수 있는지 여부를 저장
4+ dp[0]은 빈 문자열이므로 True 나머지는 False로 초기화 (총 길이가 len(s) + 1)
5+ wordDict를 순회하면서
6+ 길이 n까지의 문자열이 word로 끝나는지
7+ n - len(word) 길이가 word로 만들어질 수 있는지 (dp[n - len(word)])
8+
9+ 두 조건 만족하면 dp[n]=True
10+ dp의 마지막 성분을 return
11+
12+
13+ word의 갯수 W, 문자열 s의 길이 S
14+
15+ TC : O(S^2 * W)
16+ 각각에 대해 for문 -> S * W
17+ s에서 word와 비교할 부분문자열 만들 때 -> S
18+
19+ SC : O(S)
20+ len(s)만큼 배열 dp를 할당
21+
22+ 유의사항
23+ - dp의 첫번째 요소
24+ - if dp[n]일 때 break를 통해 최적화할 것
25+ - TC구할 때 부분문자열 구하는 복잡도 고려
26+ """
27+
28+ class Solution :
29+ def wordBreak (self , s : str , wordDict : List [str ]) -> bool :
30+ dp = [True ] + [False ] * len (s )
31+ for n in range (1 , len (s ) + 1 ):
32+ for word in wordDict :
33+ if s [n - len (word ):n ] == word and dp [n - len (word )]:
34+ dp [n ] = True
35+ if dp [n ]:
36+ break
37+ return dp [- 1 ]
You can’t perform that action at this time.
0 commit comments