File tree Expand file tree Collapse file tree 1 file changed +34
-0
lines changed Expand file tree Collapse file tree 1 file changed +34
-0
lines changed Original file line number Diff line number Diff line change 1+ /*
2+ * 조건
3+ * 영어소문자로만 구성되어있음
4+ * wordDict안에 있는 문자를 가지고 s를 만들 수 있으면 true return
5+
6+ * 아이디어
7+ * wordDict안에 있는 단어들 중 s의 prefix 단어를 찾는다.
8+ * prefix가 되는 단어를 뺀, 나머지 뒤의 문자열이 wordDict안에 있는 단어로 시작되는지 찾는다.
9+ * 이 과정을 반복해서, s의 길이가 0이 되면 true를 리턴한다.
10+ * wordDict안에 있는 단어를 다 조회해도 s가 남아있다면 false를 리턴한다.
11+ */
12+
13+ function wordBreak ( s : string , wordDict : string [ ] ) : boolean {
14+ const memo : Record < string , boolean > = { } ;
15+ return isBreak ( s , wordDict , memo ) ;
16+ }
17+
18+ function isBreak ( s : string , wordDict : string [ ] , memo : Record < string , boolean > ) {
19+ if ( s . length === 0 ) return true ;
20+ if ( s in memo ) return memo [ s ] ;
21+ for ( const word of wordDict ) {
22+ const length = word . length ;
23+ if ( s . startsWith ( word ) && isBreak ( s . slice ( length ) , wordDict , memo ) ) {
24+ memo [ s ] = true ;
25+ return true ;
26+ }
27+ }
28+
29+ memo [ s ] = false ;
30+ return false ;
31+ }
32+ // TC: O(s*w)
33+ // SC: O(s)
34+ // s: s.length, w: wordDict.length
You can’t perform that action at this time.
0 commit comments