-
Notifications
You must be signed in to change notification settings - Fork 229
/
Copy path1249-minimum-remove-to-make-valid-parentheses.js
75 lines (70 loc) · 1.46 KB
/
1249-minimum-remove-to-make-valid-parentheses.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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
/**
* @param {string} s
* @return {string}
*/
const minRemoveToMakeValid = function(s) {
const stack = [], n = s.length
const arr = s.split('')
let res = ''
for(let i = 0; i < n; i++) {
if(s[i] === '(') stack.push(i + 1)
if(s[i] === ')') {
if(stack.length && stack[stack.length - 1] >= 0) stack.pop()
else stack.push(-(i + 1))
}
}
while(stack.length) {
arr[Math.abs(stack.pop()) - 1] = ''
}
return arr.join('')
};
// another
/**
* @param {string} s
* @return {string}
*/
const minRemoveToMakeValid = function(s) {
let cnt = 0
let res = s.split('')
// console.log(res)
for(let i = 0; i < res.length; ) {
const ch = res[i]
if(ch === '(') cnt++
if(ch === ')') cnt--
if(cnt < 0) {
// console.log(res, i)
res.splice(i, 1)
cnt++
} else i++
}
// console.log(res)
let idx = res.length - 1
while(cnt > 0) {
if(res[idx] === '(') {
res.splice(idx, 1)
cnt--
} else idx--
}
return res.join('')
};
// another
/**
* @param {string} s
* @return {string}
*/
const minRemoveToMakeValid = function(s) {
const stk = [], arr = s.split(''), n = s.length
for(let i = 0; i < n; i++) {
if(s[i] === '(') stk.push(i)
if(s[i] === ')') {
if(stk.length && stk[stk.length - 1] >= 0) stk.pop()
else stk.push(-(i + 1))
}
}
while(stk.length) {
const tmp = stk.pop()
if(tmp < 0) arr[-tmp - 1] = ''
else arr[tmp] = ''
}
return arr.join('')
};