【LeetCode】139. Word Break 单词拆分(Medium)(JAVA)
题目地址: https://leetcode.com/problems/word-break/
题目描述:
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
题目大意
给定一个非空字符串 s 和一个包含非空单词的列表 wordDict,判定 s 是否可以被空格拆分为一个或多个在字典中出现的单词。
说明:
- 拆分时可以重复使用字典中的单词。
- 你可以假设字典中没有重复的单词。
解题方法
暴力解法
- 暴力解法就是通过迭代 + 记录当前的结果
- 抽取迭代公共方法:假如 string temp = s.substring(0, k) 在 wordDict 数组里面,下一步要怎么办呢?
- 就当做 s 的前面 k 个元素不存在,从 s 的第 k 个元素开始,重新做一遍 wordBreak 的操作(当然这里要保留前面得到的结果,不是真的重做),并保留返回结果
class Solution {
public boolean wordBreak(String s, List<String> wordDict) {
Set<String> set = new HashSet<>(wordDict);
return wH(s, set, 0, new HashMap<>());
}
public boolean wH(String s, Set<String> set, int start, Map<Integer, Boolean> map) {
if (start >= s.length()) return true;
if (map.get(start) != null) return map.get(start);
for (int i = start; i < s.length(); i++) {
if (!set.contains(s.substring(start, i + 1))) continue;
if (wH(s, set, i + 1, map)) {
map.put(start, true);
return true;
}
}
map.put(start, false);
return false;
}
}
执行耗时:7 ms,击败了71.20% 的Java用户
内存消耗:39.1 MB,击败了22.67% 的Java用户
动态规划
- 用动态规划函数 dp[i + 1] 表示 string s 在 i 位置的前面是否是可以分割的
- 从 i 到 0 循环,如果 s 在 [j, i] 的子串是在 wordDict 的,dp[i + 1] 的结果就是 dp[j] 的结果,知道找到为 true 就不需要再遍历了
class Solution {
public boolean wordBreak(String s, List<String> wordDict) {
if (s.length() <= 0) return true;
Set<String> set = new HashSet<>(wordDict);
boolean[] dp = new boolean[s.length() + 1];
dp[0] = true;
for (int i = 0; i < s.length(); i++) {
for (int j = i; j >= 0 && !dp[i + 1]; j--) {
String cur = s.substring(j, i + 1);
if (!set.contains(cur)) continue;
dp[i + 1] = dp[j];
}
}
return dp[s.length()];
}
}
执行耗时:6 ms,击败了74.31% 的Java用户
内存消耗:38.7 MB,击败了67.26% 的Java用户
![](https://i-blog.csdnimg.cn/blog_migrate/6c56d31f951aece27c5faae608dfac2e.jpeg)