给定一个非空字符串 s 和一个包含非空单词列表的字典 wordDict,判定 s 是否可以被空格拆分为一个或多个在字典中出现的单词。
说明:
拆分时可以重复使用字典中的单词。
你可以假设字典中没有重复的单词。
示例 1:
输入: s = “leetcode”, wordDict = [“leet”, “code”]
输出: true
解释: 返回 true 因为 “leetcode” 可以被拆分成 “leet code”。
示例 2:
输入: s = “applepenapple”, wordDict = [“apple”, “pen”]
输出: true
解释: 返回 true 因为 “applepenapple” 可以被拆分成 “apple pen apple”。
注意你可以重复使用字典中的单词。
示例 3:
输入: s = “catsandog”, wordDict = [“cats”, “dog”, “sand”, “and”, “cat”]
输出: false
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/word-break
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
- bfs
开始没有考虑到用一个vis记录,用来剪枝,所以运行超时,也get到可以直接用index判断是否可以与字符从左到右的匹配。比之前一个个charAt要省时。
class Solution {
public boolean wordBreak(String s, List<String> wordDict) {
Queue<String> queue = new LinkedList<>();
queue.add(s);
Set<String> vis = new HashSet<>();
vis.add(s);
while (!queue.isEmpty()) {
int size = queue.size();
for(int k = 0; k < size; k++) {
String poll = queue.poll();
int lenth = poll.length();
for (String word : wordDict) {
int len = 0;
if(word.length() > lenth) continue;
if(poll.indexOf(word) == 0) {
String t = poll.substring(word.length());
if(t.length() == 0) {
return true;
}
if(vis.contains(t)) continue;
vis.add(t);
queue.add(t);
}
}
}
}
return false;
}
}
- 动态规划
class Solution {
public boolean wordBreak(String s, List<String> wordDict) {
boolean[] dp = new boolean[s.length() + 1];
dp[0] = true;
Set<String> wordDictSet = new HashSet<>(wordDict);
for(int i = 1; i <= s.length(); i++) {
for(int j = 0; j < i; j++) {
if(dp[j] && wordDictSet.contains(s.substring(j,i))) {
dp[i] = true;
break;
}
}
}
return dp[s.length()];
}
}