標籤:cat 分析 lin map pre solution substr break 一個
題目:
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. You may assume the dictionary does not contain duplicate words.
Return all such possible sentences.
For example, given
s = "catsanddog",
dict = ["cat", "cats", "and", "sand", "dog"].
A solution is ["cats and dog", "cat sand dog"].
題意及分析:給出一個字串和一個字典,求能用字典裡的單詞將字串分割的所有可能。使用深度遍曆的方法,每次判斷字串是否以字典中的單詞為開頭,如果是開頭,繼續判斷剩餘的字串;如果最後字串長度為0,那麼就找到了能分割字串的單片語成。這裡用一個hashMap儲存中間結果,否則會逾時。
代碼:
class Solution { public List<String> wordBreak(String s, List<String> wordDict) { return DFS(s, wordDict, new HashMap<String, LinkedList<String>>()); } List<String> DFS(String s,List<String> wordDict,HashMap<String,LinkedList<String>> map){ if(map.containsKey(s)) return map.get(s); LinkedList<String> res = new LinkedList<>(); if(s.length() == 0){ res.add(""); return res; } for(String word : wordDict){ if(s.startsWith(word)){ List<String> subList = DFS(s.substring(word.length()),wordDict,map); for(String sub : subList){ res.add(word + (sub.isEmpty() ? "":" ")+ sub); } } } map.put(s,res); return res; }}
[LeetCode] 140. Word Break II java