Open Tcdian opened 3 years ago
/**
* @param {string} s
* @param {string[]} wordDict
* @return {string[]}
*/
var wordBreak = function(s, wordDict) {
const direction = new Set();
for (let i = 0; i < wordDict.length; i++) {
direction.add(wordDict[i]);
}
const cache = new Map();
return _wordBreak(s);
function _wordBreak(s) {
if (cache.has(s)) {
return cache.get(s);
}
const result = direction.has(s) ? [s] : [];
for (let i = 0; i < s.length; i++) {
const word = s.slice(i);
if (direction.has(word)) {
const others = _wordBreak(s.slice(0, i));
for (let j = 0; j < others.length; j++) {
result.push (`${others[j]} ${word}`);
}
}
}
cache.set(s, result);
return result;
}
};
function wordBreak(s: string, wordDict: string[]): string[] {
const direction: Set<string> = new Set();
for (let i = 0; i < wordDict.length; i++) {
direction.add(wordDict[i]);
}
const cache: Map<string, string[]> = new Map();
return _wordBreak(s);
function _wordBreak(s: string): string[] {
if (cache.has(s)) {
return cache.get(s) as string[];
}
const result: string[] = direction.has(s) ? [s] : [];
for (let i = 0; i < s.length; i++) {
const word = s.slice(i);
if (direction.has(word)) {
const others = _wordBreak(s.slice(0, i));
for (let j = 0; j < others.length; j++) {
result.push(`${others[j]} ${word}`);
}
}
}
cache.set(s, result);
return result;
}
};
140. Word Break II
给定一个 非空 字符串
s
和一个包含 非空 单词列表的字典wordDict
,在字符串中增加空格来构建一个句子,使得句子中所有的单词都在词典中。返回所有这些可能的句子。Note
Example 1
Example 2
Example 3