File tree Expand file tree Collapse file tree 1 file changed +51
-0
lines changed Expand file tree Collapse file tree 1 file changed +51
-0
lines changed Original file line number Diff line number Diff line change
1
+ /**
2
+ * [Problem]: [139] Word Break
3
+ * (https://leetcode.com/problems/word-break/description/)
4
+ */
5
+ function wordBreak ( s : string , wordDict : string [ ] ) : boolean {
6
+ //시간복잡도: O(n^2)
7
+ //공간복잡도: O(n)
8
+ function dfsFunc ( s : string , wordDict : string [ ] ) : boolean {
9
+ let wordSet = new Set ( wordDict ) ;
10
+ let memo = new Map < number , boolean > ( ) ;
11
+
12
+ function dfs ( start : number ) : boolean {
13
+ if ( start === s . length ) return true ;
14
+ if ( memo . has ( start ) ) return memo . get ( start ) ! ;
15
+
16
+ for ( let end = start + 1 ; end <= s . length ; end ++ ) {
17
+ const word = s . slice ( start , end ) ;
18
+
19
+ if ( wordSet . has ( word ) && dfs ( end ) ) {
20
+ memo . set ( start , true ) ;
21
+ return true ;
22
+ }
23
+ }
24
+
25
+ memo . set ( start , false ) ;
26
+ return false ;
27
+ }
28
+
29
+ return dfs ( 0 ) ;
30
+ }
31
+
32
+ //시간복잡도: O(n^2)
33
+ //공간복잡도: O(n)
34
+ function dpFunc ( s : string , wordDict : string [ ] ) : boolean {
35
+ const wordSet = new Set ( wordDict ) ;
36
+ const dp = new Array ( s . length + 1 ) . fill ( false ) ;
37
+ dp [ 0 ] = true ;
38
+
39
+ for ( let end = 1 ; end <= s . length ; end ++ ) {
40
+ for ( let start = 0 ; start < end ; start ++ ) {
41
+ const isExists = wordSet . has ( s . slice ( start , end ) ) ;
42
+ if ( isExists && dp [ start ] ) {
43
+ dp [ end ] = true ;
44
+ break ;
45
+ }
46
+ }
47
+ }
48
+ return dp [ s . length ] ;
49
+ }
50
+ return dpFunc ( s , wordDict ) ;
51
+ }
You can’t perform that action at this time.
0 commit comments