Skip to content

Commit 903cc8d

Browse files
authored
Update 1541-minimum-insertions-to-balance-a-parentheses-string.js
1 parent fcb3a02 commit 903cc8d

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

1541-minimum-insertions-to-balance-a-parentheses-string.js

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,34 @@
1+
/**
2+
* @param {string} s
3+
* @return {number}
4+
*/
5+
const minInsertions = function(s) {
6+
let insert = 0, idx = 0, open = 0, len = s.length
7+
while(idx < len) {
8+
const ch = s[idx]
9+
if(ch === '(') {
10+
open++
11+
idx++
12+
} else {
13+
if(open > 0) {
14+
open--
15+
} else {
16+
insert++
17+
}
18+
if(idx < len - 1 && s[idx + 1] === ')') {
19+
idx += 2
20+
} else {
21+
insert++
22+
idx++
23+
}
24+
}
25+
}
26+
if(open) insert += open * 2
27+
return insert
28+
};
29+
30+
// another
31+
132
/**
233
* @param {string} s
334
* @return {number}

0 commit comments

Comments
 (0)