forked from everthis/leetcode-js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
1096-brace-expansion-ii.js
52 lines (50 loc) · 1.25 KB
/
1096-brace-expansion-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
/**
* @param {string} expression
* @return {string[]}
*/
const braceExpansionII = function (expression) {
expression = expression.replace(/([a-z]){1}/g, '{$1}')
const stk = new Array()
for (let char of expression) {
if (char !== '}') {
stk.push(char)
} else {
let str = '',
prev = '',
temp = ''
while (stk[stk.length - 1] != '{') {
prev = temp
temp = stk.pop()
if (temp == ',' || prev == ',' || str == '') str = temp + str
else {
str = str
.split(',')
.map((item) => {
let ar = new Array()
for (let ch of temp.split(',')) ar.push(ch + item)
return ar.join(',')
})
.join(',')
}
}
stk.pop()
while (
stk.length > 0 &&
stk[stk.length - 1] != ',' &&
stk[stk.length - 1] != '{'
) {
temp = stk.pop()
str = str
.split(',')
.map((item) => {
let ar = new Array()
for (let ch of temp.split(',')) ar.push(ch + item)
return ar.join(',')
})
.join(',')
}
if (str.length > 0) stk.push(str)
}
}
return [...new Set(stk[0].split(','))].sort()
}