題目描述:給定非空字符串s和包含非空單詞列表的字典wordDict,確定是否可以將s分割為一個(gè)或多個(gè)字典中所包含的單詞序列(通過空格區(qū)分)。
說明:
1.詞典中的同一個(gè)詞可以在分割中重復(fù)使用多次
- 你可以假設(shè)字典不包含重復(fù)的單詞
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
通過函數(shù)遞歸調(diào)用判斷是否包含:
class Solution {
Set<String> set=new HashSet<>();
public boolean wordBreak(String s, List<String> 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;
}
}