0140. Word Break II (H)

Word Break II (H)

题目

Given a non-empty string s and a dictionary wordDict containing a list of non-empty words, add spaces in s to construct a sentence where each word is a valid dictionary word. Return all such possible sentences.

Note:

  • 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 = "catsanddog"
wordDict = ["cat", "cats", "and", "sand", "dog"]
Output:
[
  "cats and dog",
  "cat sand dog"
]

Example 2:

Input:
s = "pineapplepenapple"
wordDict = ["apple", "pen", "applepen", "pine", "pineapple"]
Output:
[
  "pine apple pen apple",
  "pineapple pen apple",
  "pine applepen apple"
]
Explanation: Note that you are allowed to reuse a dictionary word.

Example 3:

Input:
s = "catsandog"
wordDict = ["cats", "dog", "sand", "and", "cat"]
Output:
[]

题意

判断给定字符串按照某种方式分割后得到的所有子串能否在给定数组中找到,并返回所有可能的分割方式。

思路

  1. Word Break 威力加强版。使用记忆化DFS搜索处理。在139题的基础上进行改动:HashMap记录字符串s中以下标start为起点的子字符串的所有分割方式(如果无法有效分割则为空)。

代码实现

Java

class Solution {
    Map<Integer, List<String>> hash = new HashMap<>();

    public List<String> wordBreak(String s, List<String> wordDict) {
        return dfs(s, 0, wordDict);
    }

    private List<String> dfs(String s, int start, List<String> wordDict) {
        if (hash.containsKey(start)) {
            return hash.get(start);
        }

        List<String> res = new ArrayList<>();
        
        // 边界处理,说明这种分割方式有效,添加空字符串方便处理
        if (start == s.length()) {
            res.add("");
            return res;
        }

        for (String word : wordDict) {
            // 每次先找到下一个能有效分割的位置
            if (s.substring(start).startsWith(word)) {
                List<String> next = dfs(s, start + word.length(), wordDict);
                for (String t : next) {
                    // 注意空格的处理
                    if (!t.isEmpty()) {
                        t = " " + t;
                    }
                    res.add(word + t);
                }
            }
        }

        // 如果以start为起点的子串不能有效分割,则返回的res是一个空list
        hash.put(start, res);
        return res;	
    }
}

JavaScript

/**
 * @param {string} s
 * @param {string[]} wordDict
 * @return {string[]}
 */
var wordBreak = function (s, wordDict) {
  return dfs(s, 0, new Map([[s.length, [[]]]]), wordDict).map(v => v.join(' '))
}

let dfs = function (s, index, record, wordDict) {
  if (record.has(index)) {
    return record.get(index)
  }

  let lists = []
  for (let word of wordDict) {
    if (s.slice(index).startsWith(word)) {
      let next = dfs(s, index + word.length, record, wordDict)
      for (let list of next) {
        let tmp = [...list]
        tmp.unshift(word)
        lists.push(tmp)
      }
    }
  }

  record.set(index, lists)
  return lists
}
posted @ 2020-07-31 10:41  墨云黑  阅读(191)  评论(0编辑  收藏  举报