Skip to content

Commit 2adc62b

Browse files
authored
Update 1764-form-array-by-concatenating-subarrays-of-another-array.js
1 parent 8f765dc commit 2adc62b

File tree

1 file changed

+56
-0
lines changed

1 file changed

+56
-0
lines changed

1764-form-array-by-concatenating-subarrays-of-another-array.js

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,59 @@
1+
/**
2+
* @param {number[][]} groups
3+
* @param {number[]} nums
4+
* @return {boolean}
5+
*/
6+
const canChoose = function (groups, nums) {
7+
const dp = new Array(1000).fill(0)
8+
const lsps = preprocess(groups)
9+
let cur = 0
10+
for (let i = 0; i < groups.length; i++) {
11+
if (cur >= nums.length) return false
12+
cur = find(nums, cur, groups[i], lsps[i])
13+
if (cur === -1) return false
14+
cur += groups[i].length
15+
}
16+
return true
17+
function find(nums, cur, p, lsp) {
18+
const n = nums.length
19+
dp[cur] = p[0] === nums[cur] ? 1 : 0
20+
if (lsp.length === 1 && dp[cur] === 1) {
21+
return cur
22+
}
23+
for (let i = cur + 1; i < n; i++) {
24+
let j = dp[i - 1]
25+
while (j > 0 && p[j] !== nums[i]) {
26+
j = lsp[j - 1]
27+
}
28+
dp[i] = j + (p[j] === nums[i])
29+
if (dp[i] === p.length) {
30+
return i - p.length + 1
31+
}
32+
}
33+
return -1
34+
}
35+
36+
function preprocess(groups) {
37+
const rets = []
38+
for (let g of groups) {
39+
const n = g.length
40+
const dp = new Array(n)
41+
dp[0] = 0
42+
for (let i = 1; i < n; i++) {
43+
let j = dp[i - 1]
44+
while (j > 0 && g[j] !== g[i]) {
45+
j = dp[j - 1]
46+
}
47+
dp[i] = j + (g[j] === g[i] ? 1 : 0)
48+
}
49+
rets.push(dp)
50+
}
51+
return rets
52+
}
53+
}
54+
55+
// another
56+
157
/**
258
* @param {number[][]} groups
359
* @param {number[]} nums

0 commit comments

Comments
 (0)