1. 程式人生 > >[LeetCode] 140. Word Break II java

[LeetCode] 140. Word Break II java

contains clas emp dfs urn key 分析 超時 字典

題目:

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