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.javascript
Note:java
Example 1:數組
Input: s = "leetcode", wordDict = ["leet", "code"] Output: true Explanation: Return true because "leetcode" can be segmented as "leet code".
Example 2:app
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:spa
Input: s = "catsandog", wordDict = ["cats", "dog", "sand", "and", "cat"] Output: false
判斷給定字符串按照某種方式分割後獲得的全部子串可否在給定數組中找到。code
純DFS會超時,因此利用Map記錄下全部執行過的遞歸的結果。遞歸
動態規劃。dp[i]表明s中以第i個字符結尾的子串是否知足要求,則狀態轉移方程爲:只要有任意一個j(j<i)知足 dp[j]==true && wordDict.contains(s.substring(j,i))==true,那麼dp[i]=true。ip
class Solution { public boolean wordBreak(String s, List<String> wordDict) { return isValid(s, 0, wordDict, new HashMap<>()); } private boolean isValid(String s, int start, List<String> wordDict, Map<Integer, Boolean> record) { if (start == s.length()) { return true; } if (record.containsKey(start)) { return record.get(start); } for (int end = start + 1; end <= s.length(); end++) { if (wordDict.contains(s.substring(start, end)) && isValid(s, end, wordDict, record)) { record.put(start, true); return true; } } record.put(start, false); return false; } }
class Solution { public boolean wordBreak(String s, List<String> wordDict) { boolean[] dp = new boolean[s.length() + 1]; dp[0] = true; for (int i = 1; i <= s.length(); i++) { for (int j = 0; j < i; j++) { if (dp[j] && wordDict.contains(s.substring(j, i))) { dp[i] = true; break; } } } return dp[s.length()]; } }
/** * @param {string} s * @param {string[]} wordDict * @return {boolean} */ var wordBreak = function (s, wordDict) { let dp = new Array(s.length + 1).fill(false) dp[0] = true for (let i = 1; i <= s.length; i++) { for (let j = 0; j < i; j++) { if (dp[j] && wordDict.indexOf(s.slice(j, i)) >= 0) { dp[i] = true break } } } return dp[s.length] }