140 Word Break II
阿新 • • 發佈:2018-11-06
Given a non-empty string s and a dictionary wordDict containing a list of non-empty words, add spaces in s to construct a sentence where each word is a valid dictionary word. Return all such possible sentences. Note: * The same word in the dictionary may be reused multiple times in the segmentation.* You may assume the dictionary does not contain duplicate words. Example 1: Input: s = "catsanddog" wordDict = ["cat", "cats", "and", "sand", "dog"] Output: [ "cats and dog", "cat sand dog" ] Example 2: Input: s = "pineapplepenapple" wordDict = ["apple", "pen", "applepen", "pine", "pineapple"] Output: ["pine apple pen apple", "pineapple pen apple", "pine applepen apple" ] Explanation: Note that you are allowed to reuse a dictionary word. Example 3: Input: s = "catsandog" wordDict = ["cats", "dog", "sand", "and", "cat"] Output: [] class Solution { public List<String> wordBreak(String s, List<String> wordDict) { HashMap<String, List<String>> used = new HashMap<>(); HashSet<String> set = new HashSet<>(); List<String> res = new ArrayList<>(); for(String word : wordDict){ set.add(word); } res = helper(s, set, used); return res; } public List<String> helper(String s, HashSet<String> set, HashMap<String, List<String>> used){ if(used.containsKey(s)){ return used.get(s); } if(s.length() == 0){ return null; } List<String> res = new ArrayList<>(); for(int i = 1; i <= s.length(); i++){ String sub = s.substring(0, i); List<String> partRes = null; if(set.contains(sub)){ partRes = helper(s.substring(i), set, used); if(partRes == null){ res.add(sub); }else{ for(String str : partRes){ res.add(sub + " " + str); // " ". not "" } } } } used.put(s, res); return res; } }