Skip to content

Commit d194824

Browse files
Accepted
1 parent 7514531 commit d194824

File tree

1 file changed

+60
-0
lines changed

1 file changed

+60
-0
lines changed

problems/src/WordBreakII.java

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
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+
}

0 commit comments

Comments
 (0)