题目描述:给定非空字符串s和包含非空单词列表的字典wordDict,确定是否可以将s分割为一个或多个字典中所包含的单词序列(通过空格区分)。
说明:
1.词典中的同一个词可以在分割中重复使用多次
- 你可以假设字典不包含重复的单词
Example1:
Input: s = "leetcode", wordDict = ["leet", "code"]
Output: true
Explanation: Return true because "leetcode" can be segmented as "leet code".
Example2:
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.
Example3:
Input: s = "catsandog", wordDict = ["cats", "dog", "sand", "and", "cat"]
Output: false
通过函数递归调用判断是否包含:
class Solution {
Set set=new HashSet<>();
public boolean wordBreak(String s, List wordDict) {
if(wordDict.contains(s))
return true;
if(set.contains(s))
return false;
for(String string:wordDict){
if(s.startsWith(string)){
if(wordBreak(s.substring(string.length()),wordDict))
return true;
}
}
set.add(s);
return false;
}
}