Skip to content

Commit 8a6adea

Browse files
authored
Create 1087-brace-expansion.js
1 parent 2818931 commit 8a6adea

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed

1087-brace-expansion.js

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
/**
2+
* @param {string} S
3+
* @return {string[]}
4+
*/
5+
const expand = function(S) {
6+
const arr = []
7+
let cur = ''
8+
for (let i = 0, len = S.length; i < len; i++) {
9+
const ch = S.charAt(i)
10+
if (ch === '{') {
11+
if (cur) arr.push(cur)
12+
cur = []
13+
} else if (ch === '}') {
14+
arr.push(cur.sort())
15+
cur = ''
16+
} else if (ch === ',') {
17+
} else {
18+
if (typeof cur === 'string' || cur === '') {
19+
cur += ch
20+
} else {
21+
cur.push(ch)
22+
}
23+
}
24+
}
25+
arr.push(cur)
26+
const res = []
27+
bt(arr, 0, '', res)
28+
return res
29+
}
30+
function bt(arr, i, cur, res) {
31+
if (i === arr.length) {
32+
res.push(cur)
33+
return
34+
}
35+
if (typeof arr[i] === 'string') {
36+
cur += arr[i]
37+
bt(arr, i + 1, cur, res)
38+
} else {
39+
for (let j = 0, len = arr[i].length; j < len; j++) {
40+
let bak = cur
41+
cur += arr[i][j]
42+
bt(arr, i + 1, cur, res)
43+
cur = bak
44+
}
45+
}
46+
}

0 commit comments

Comments
 (0)