給定一個非空字符串 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
思路:背包問題變形
public class Solution {public boolean wordBreak(String s, List<String> wordDict) {Set<String> wordDictSet=new HashSet(wordDict);int len=s.length();boolean[] dp = new boolean[len + 1];dp[0] = true;for (int i = 1; i <= len; i++) {for (int j = 0; j < i; j++) {if (dp[j] && wordDictSet.contains(s.substring(j, i))) {dp[i] = true;break;}}}return dp[len];}
}
?