|
| 1 | +package hard; |
| 2 | +import java.util.*; |
| 3 | +/** |
| 4 | + * Created by fishercoder1534 on 10/4/16. |
| 5 | + */ |
| 6 | +public class WordBreakII { |
| 7 | + public List<String> wordBreak(String s, Set<String> wordDict) { |
| 8 | + return dfs(s, wordDict, new HashMap<String, ArrayList<String>>()); |
| 9 | + } |
| 10 | + |
| 11 | + private List<String> dfs(String s, Set<String> wordDict, |
| 12 | + HashMap<String, ArrayList<String>> map) { |
| 13 | + if(map.containsKey(s)){ |
| 14 | + return map.get(s); |
| 15 | + } |
| 16 | + |
| 17 | + ArrayList<String> res = new ArrayList<String>(); |
| 18 | + if(s.length() == 0){ |
| 19 | + res.add(""); |
| 20 | + return res; |
| 21 | + } |
| 22 | + |
| 23 | + for(String word : wordDict){ |
| 24 | + if(s.startsWith(word)){ |
| 25 | + List<String> subList = dfs(s.substring(word.length()), wordDict, map); |
| 26 | + for(String sub : subList){ |
| 27 | + res.add(word + (sub.length() == 0 ? "" : " ") + sub); |
| 28 | + } |
| 29 | + } |
| 30 | + } |
| 31 | + map.put(s, res); |
| 32 | + return res; |
| 33 | + } |
| 34 | + |
| 35 | + public static void main(String...strings){ |
| 36 | + List<String> temp = new ArrayList<String>(); |
| 37 | + System.out.println(temp); |
| 38 | + List<String> temp2 = new ArrayList<String>(temp); |
| 39 | + temp2.add(""); |
| 40 | + System.out.println(temp2); |
| 41 | + |
| 42 | + WordBreakII test = new WordBreakII(); |
| 43 | + Set<String> wordDict = new HashSet<>(); |
| 44 | + wordDict.add("cat"); |
| 45 | + wordDict.add("cats"); |
| 46 | + wordDict.add("sand"); |
| 47 | + wordDict.add("and"); |
| 48 | + wordDict.add("dog"); |
| 49 | + String s = "catsanddog"; |
| 50 | +// List<String> list = test.wordBreak(s, wordDict); |
| 51 | + List<String> list = test.wordBreak(s, wordDict); |
| 52 | + for(String word : list){ |
| 53 | + System.out.print(word + ", "); |
| 54 | + } |
| 55 | + System.out.println(); |
| 56 | + } |
| 57 | +} |
0 commit comments