Given a non-empty string s and a dictionary wordDict containing a list of non-empty words, determine if s can be segmented into a space-separated sequence of one or more dictionary words.
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 = "leetcode", wordDict = ["leet", "code"] Output: true Explanation: Return true because "leetcode" can be segmented as "leet code". Example 2: Input: s = "applepenapple", wordDict = ["apple", "pen"] Output: true Explanation: Return true because "applepenapple" can be segmented as "apple pen apple". Note that you are allowed to reuse a dictionary word. Example 3: Input: s = "catsandog", wordDict = ["cats", "dog", "sand", "and", "cat"] Output: false使用树的dfs来做: 看字符串s是否有分叉,依次用substring分割字符串,找到一个在dict中存在的字符串时,就代表它可以从此处进行分叉, 进入子树,然后继续使用dfs,搜索剩下的字符串。
class Solution { public boolean wordBreak(String s, List<String> wordDict) { Set<String> dict = new HashSet<>(wordDict); return dfs(s, 0, dict); } private boolean dfs(String s, int start, Set<String> dict) { if (start == s.length()) { return true; } for (int i = start; i < s.length(); i++) { String word = s.substring(start, i + 1); if (dict.contains(word)) { if (dfs(s, i + 1, dict)) { return true; } } } return false; } }问题: 会超时。原因是有很多大量的重复计算,比如说某一个start位置已经计算过了,另外的分叉的到了这个start位置后,还是会重新计算一遍。 解决: 使用Map<Integer, boolean>来存储每个start位置的结果即可。后面又到了这个start的地方的话,就可以先查一下结果,没有再去算。缓存的思想。 优化: 可以使用一个数组来存这个结果,不过需要存Boolean类型,用null代表没有结果。 不能用boolean[],因为这样所有的值都初始化了false。要使用Boolean[] 所有值为null
class Solution { public boolean wordBreak(String s, List<String> wordDict) { Set<String> dict = new HashSet<>(wordDict); Boolean[] results = new Boolean[s.length() + 1]; return dfs(s, 0, dict, results); } private boolean dfs(String s, int start, Set<String> dict, Boolean[] results) { // 缓存,之前的答案 if (results[start] != null) { return results[start]; } if (start == s.length()) { return true; } for (int i = start; i < s.length(); i++) { String word = s.substring(start, i + 1); if (dict.contains(word)) { if (dfs(s, i + 1, dict, results)) { // 返回答案前,存入缓存 results[start] = true; return true; } } } // 返回答案前,存入缓存 results[start] = false; return false; } }使用DP: 从后往前看,如果substring(i, end)在dict里面,且results[end] = true, 则results[i] = true
class Solution { public boolean wordBreak(String s, List<String> wordDict) { int n = s.length(); Set<String> dict = new HashSet<>(wordDict); boolean[] results = new boolean[n + 1]; results[n] = true; for (int i = n - 1; i >= 0; i--) { for (int end = i + 1; end <= n; end++) { if (dict.contains(s.substring(i, end)) && results[end]) { results[i] = true; } } } return results[0]; } }