Skip to content

Commit 0e5b74e

Browse files
committed
Add solution #1541
1 parent 560e92d commit 0e5b74e

File tree

2 files changed

+50
-1
lines changed

2 files changed

+50
-1
lines changed

README.md

+2-1
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
# 1,355 LeetCode solutions in JavaScript
1+
# 1,356 LeetCode solutions in JavaScript
22

33
[https://leetcodejavascript.com](https://leetcodejavascript.com)
44

@@ -1177,6 +1177,7 @@
11771177
1537|[Get the Maximum Score](./solutions/1537-get-the-maximum-score.js)|Hard|
11781178
1539|[Kth Missing Positive Number](./solutions/1539-kth-missing-positive-number.js)|Easy|
11791179
1540|[Can Convert String in K Moves](./solutions/1540-can-convert-string-in-k-moves.js)|Medium|
1180+
1541|[Minimum Insertions to Balance a Parentheses String](./solutions/1541-minimum-insertions-to-balance-a-parentheses-string.js)|Medium|
11801181
1550|[Three Consecutive Odds](./solutions/1550-three-consecutive-odds.js)|Easy|
11811182
1551|[Minimum Operations to Make Array Equal](./solutions/1551-minimum-operations-to-make-array-equal.js)|Medium|
11821183
1566|[Detect Pattern of Length M Repeated K or More Times](./solutions/1566-detect-pattern-of-length-m-repeated-k-or-more-times.js)|Easy|
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
/**
2+
* 1541. Minimum Insertions to Balance a Parentheses String
3+
* https://leetcode.com/problems/minimum-insertions-to-balance-a-parentheses-string/
4+
* Difficulty: Medium
5+
*
6+
* Given a parentheses string s containing only the characters '(' and ')'. A parentheses string
7+
* is balanced if:
8+
* - Any left parenthesis '(' must have a corresponding two consecutive right parenthesis '))'.
9+
* - Left parenthesis '(' must go before the corresponding two consecutive right parenthesis '))'.
10+
*
11+
* In other words, we treat '(' as an opening parenthesis and '))' as a closing parenthesis.
12+
* - For example, "())", "())(())))" and "(())())))" are balanced, ")()", "()))" and "(()))" are
13+
* not balanced.
14+
*
15+
* You can insert the characters '(' and ')' at any position of the string to balance it if needed.
16+
*
17+
* Return the minimum number of insertions needed to make s balanced.
18+
*/
19+
20+
/**
21+
* @param {string} s
22+
* @return {number}
23+
*/
24+
var minInsertions = function(s) {
25+
let result = 0;
26+
let openCount = 0;
27+
28+
for (let i = 0; i < s.length; i++) {
29+
if (s[i] === '(') {
30+
openCount++;
31+
} else {
32+
if (i + 1 < s.length && s[i + 1] === ')') {
33+
i++;
34+
} else {
35+
result++;
36+
}
37+
if (openCount > 0) {
38+
openCount--;
39+
} else {
40+
result++;
41+
}
42+
}
43+
}
44+
45+
result += openCount * 2;
46+
47+
return result;
48+
};

0 commit comments

Comments
 (0)