0139. Word Break (M)

Word Break (M)

題目

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

  • The same word in the dictionary may be reused multiple times in the segmentation.
  • You may assume the dictionary does not contain duplicate words.

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

思路

  1. 純DFS會超時,因此利用Map記錄下全部執行過的遞歸的結果。遞歸

  2. 動態規劃。dp[i]表明s中以第i個字符結尾的子串是否知足要求,則狀態轉移方程爲:只要有任意一個j(j<i)知足 dp[j]==true && wordDict.contains(s.substring(j,i))==true,那麼dp[i]=true。ip


代碼實現

Java

記憶化搜索

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()];
    }
}

JavaScript

/**
 * @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]
}
相關文章
相關標籤/搜索