File tree Expand file tree Collapse file tree 1 file changed +33
-0
lines changed Expand file tree Collapse file tree 1 file changed +33
-0
lines changed Original file line number Diff line number Diff line change
1
+ /*
2
+
3
+ Time Complexity: O(s * L^2)
4
+ - L is max length of wordDict[i]
5
+ Space Complexity: O(s + w * L)
6
+ */
7
+ class Solution {
8
+ public boolean wordBreak (String s , List <String > wordDict ) {
9
+ Set <String > wordSet = new HashSet <>();
10
+ int maxLen = 0 ;
11
+ for (String word : wordDict ) {
12
+ wordSet .add (word );
13
+ maxLen = Math .max (maxLen , word .length ());
14
+ }
15
+
16
+ boolean [] dp = new boolean [s .length () + 1 ];
17
+ dp [0 ] = true ;
18
+
19
+ for (int i = 0 ; i < s .length (); i ++) {
20
+ for (int j = 1 ; j <= maxLen ; j ++) {
21
+ int beginIdx = i - j + 1 ;
22
+ if (beginIdx < 0 )
23
+ continue ;
24
+ if (wordSet .contains (s .substring (beginIdx , i + 1 )) && dp [beginIdx ]) {
25
+ dp [i + 1 ] = true ;
26
+ break ;
27
+ }
28
+ }
29
+ }
30
+
31
+ return dp [s .length ()];
32
+ }
33
+ }
You can’t perform that action at this time.
0 commit comments