-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path140.单词拆分-ii.js
56 lines (52 loc) · 1.29 KB
/
140.单词拆分-ii.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
/*
* @lc app=leetcode.cn id=140 lang=javascript
*
* [140] 单词拆分 II
*/
/**
* @param {string} s
* @param {string[]} wordDict
* @return {string[]}
*/
var wordBreak = function(s, wordDict) {
let arr = []
if (!canWordBreak(s, wordDict)) {
return arr
}
for (let i = 1; i <= s.length; i++) {
const position = wordDict.indexOf(s.substr(0, i))
if (position > -1) {
if (i === s.length) {
arr.push(s)
break
}
const list = wordBreak(s.substr(i, s.length), wordDict)
list.forEach(res => {
const resultArr = s.substr(0, i) + ' ' + res
arr.push(resultArr)
})
}
}
return arr
}
function canWordBreak(s, wordDict) {
let diction = new Array(s.length + 1)
diction[0] = true
for (let i = 0; i < s.length; i++) {
let son_str = s.substring(0, i + 1) //长度从1到str.lenth一遍一遍来
if (wordDict.indexOf(son_str) != -1) {
diction[i + 1] = true
continue
}
for (let j = 0; j < son_str.length; j++) {
let right_son_str = son_str.substring(j + 1, i + 1) //长度从1到str.lenth一遍一遍来
if (diction[j + 1] && wordDict.indexOf(right_son_str) != -1) {
diction[i + 1] = true
}
}
}
if (null == diction[s.length]) {
return false
}
return diction[s.length]
}