deno.land / x / masx200_leetcode_test@10.6.5 / different-ways-to-add-parentheses / index.ts

نووسراو ببینە
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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
export default function diffWaysToCompute(expression: string): number[] { if (/^\d+$/g.test(expression)) { return [Number(expression)]; } const regexp = /(?<operator>[\+\-\*])|(?<digit>\d+)/g; const groups = Array.from(expression.matchAll(regexp)).map( (a) => a.groups, ) as unknown as ( | { digit: string; operator?: undefined; } | { digit?: undefined; operator: string; } )[]; const ans: number[] = diffWaysCalc(groups); return ans;}function diffWaysCalc( groups: ( | { digit: number | string; operator?: undefined; } | { digit?: undefined; operator: string; } )[],): number[] { if (groups.length === 1) { return [Number(groups[0].digit)]; } if (groups.length === 3) { return [calc_three(groups)]; }
const ans: number[] = []; for (let i = 1; i < groups.length; i += 2) { const operator = groups[i]; const left = diffWaysCalc(groups.slice(0, i)); const right = diffWaysCalc(groups.slice(i + 1));
left.map((a) => right.map((b) => calc_three([{ digit: a }, operator, { digit: b }])) ).forEach((a) => ans.push(...a)); } return ans;}function calc_three( groups: ( | { digit: number | string; operator?: undefined; } | { digit?: undefined; operator: string; } )[],): number { if (groups.length === 3) { const [a, b, c] = groups; if (b.operator === "+") { return Number(a.digit) + Number(c.digit); } if (b.operator === "-") { return Number(a.digit) - Number(c.digit); } if (b.operator === "*") { return Number(a.digit) * Number(c.digit); } } throw Error("groups length not three or operator not +,-,*");}
masx200_leetcode_test

Version Info

Tagged at
a year ago