139. Word Break

素颜马尾好姑娘i 2022-02-13 10:43 294阅读 0赞
  1. 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.
  2. Note:
  3. The same word in the dictionary may be reused multiple times in the segmentation.
  4. You may assume the dictionary does not contain duplicate words.
  5. Example 1:
  6. Input: s = "leetcode", wordDict = ["leet", "code"]
  7. Output: true
  8. Explanation: Return true because "leetcode" can be segmented as "leet code".
  9. Example 2:
  10. Input: s = "applepenapple", wordDict = ["apple", "pen"]
  11. Output: true
  12. Explanation: Return true because "applepenapple" can be segmented as "apple pen apple".
  13. Note that you are allowed to reuse a dictionary word.
  14. Example 3:
  15. Input: s = "catsandog", wordDict = ["cats", "dog", "sand", "and", "cat"]
  16. Output: false

本题使用动态规划的方法可以轻松解决。

  1. public boolean wordBreak(String s, List<String> wordDict) {
  2. boolean[] dp = new boolean[s.length() + 1];//dp[i]代表s.subString(0, i)可以使用wordDict里面的词分割
  3. dp[0] = true;//设置初始条件;s.subString(0, 0)当然满足要求
  4. for(int i = 1; i <= s.length(); ++i) {//依次判断dp[i]的分割序列是否分别存在于wordDict里面
  5. for(int j = 0; j < i; ++j) {
  6. if(dp[j] && wordDict.contains(s.substring(j, i))) {//dp[j]的分割序列和s.substring(j, i)都存在于wordDict里面
  7. dp[i] = true;
  8. break;
  9. }
  10. }
  11. }
  12. return dp[s.length()];
  13. }

PS:做了140. Word Break II之后,发现还可以使用DFS的方法来解答。

  1. public boolean wordBreak(String s, List<String> wordDict) {
  2. Map<String, Boolean> map = new HashMap<>();//dp.get(s)表示s的分割集是否都存在于wordDict里
  3. map.put("", true);//初始化
  4. return DFS(s, wordDict, map);
  5. }
  6. private boolean DFS(String s, List<String> wordDict, Map<String, Boolean> map) {
  7. if(map.containsKey(s)) {
  8. return map.get(s);
  9. }
  10. for(int i = 0; i < wordDict.size(); ++i) {
  11. String word = wordDict.get(i);
  12. if(s.startsWith(word) && DFS(s.substring(word.length()), wordDict, map)) {
  13. map.put(s, true);
  14. return true;
  15. }
  16. }
  17. map.put(s, false);
  18. return false;
  19. }

发表评论

表情:
评论列表 (有 0 条评论,294人围观)

还没有评论,来说两句吧...

相关阅读

    相关 139.Word Break(断字符串)

    题目: 给定一个非空字符串s和包含非空单词列表的字典wordDict,请确定s是否可以分段为一个或多个字典单词的以空格分隔的序列。 注意: 字典中的同一单词可以在分割