File tree Expand file tree Collapse file tree 1 file changed +60
-0
lines changed Expand file tree Collapse file tree 1 file changed +60
-0
lines changed Original file line number Diff line number Diff line change
1
+ import java .util .*;
2
+
3
+ /**
4
+ * Created by gouthamvidyapradhan on 07/04/2017.
5
+ * Accepted
6
+ */
7
+ public class WordBreakII
8
+ {
9
+ private Map <Integer , List <String >> map ;
10
+ /**
11
+ * Main method
12
+ * @param args
13
+ * @throws Exception
14
+ */
15
+ public static void main (String [] args ) throws Exception
16
+ {
17
+ List <String > wordList = new ArrayList <>();
18
+ wordList .add ("cat" );
19
+ wordList .add ("cats" );
20
+ wordList .add ("and" );
21
+ wordList .add ("sand" );
22
+ wordList .add ("dog" );
23
+ System .out .println (new WordBreakII ().wordBreak ("catsanddog" , wordList ));
24
+ }
25
+
26
+ public List <String > wordBreak (String s , List <String > wordDict )
27
+ {
28
+ if (s == null ) return new ArrayList <>();
29
+ map = new HashMap <>();
30
+ Set <String > dictionary = new HashSet <>();
31
+ dictionary .addAll (wordDict );
32
+ return dp (0 , s , s .length (), dictionary );
33
+ }
34
+
35
+ private List <String > dp (int p , String s , int l , Set <String > dictionary )
36
+ {
37
+ List <String > result = new ArrayList <>();
38
+ if (p >= s .length ())
39
+ {
40
+ result .add ("" );
41
+ return result ;
42
+ }
43
+ else if (map .containsKey (p ))
44
+ {
45
+ return map .get (p );
46
+ }
47
+ for (int i = p ; i < l ; i ++)
48
+ {
49
+ String subStr = s .substring (p , i + 1 );
50
+ if (dictionary .contains (subStr ))
51
+ {
52
+ List <String > subList = dp (i + 1 , s , l , dictionary );
53
+ for (String se : subList )
54
+ result .add ((subStr + " " + se ).trim ());
55
+ }
56
+ }
57
+ map .put (p , result );
58
+ return result ;
59
+ }
60
+ }
You can’t perform that action at this time.
0 commit comments