8000 solve problem Minimum Add To Make Parentheses Valid · P-ppc/leetcode@37de491 · GitHub
[go: up one dir, main page]

Skip to content

Commit 37de491

Browse files
committed
solve problem Minimum Add To Make Parentheses Valid
1 parent b370d0b commit 37de491

File tree

5 files changed

+47
-0
lines changed

5 files changed

+47
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -302,6 +302,7 @@ All solutions will be accepted!
302302
|238|[Product Of Array Except Self](https://leetcode-cn.com/problems/product-of-array-except-self/description/)|[java/py/js](./algorithms/ProductOfArrayExceptSelf)|Medium|
303303
|896|[Monotonic Array](https://leetcode-cn.com/problems/monotonic-array/description/)|[java/py/js](./algorithms/MonotonicArray)|Easy|
304304
|739|[Daily Temperatures](https://leetcode-cn.com/problems/daily-temperatures/description/)|[java/py/js](./algorithms/DailyTemperatures)|Medium|
305+
|921|[Minimum Add To Make Parentheses Valid](https://leetcode-cn.com/problems/minimum-add-to-make-parentheses-valid/description/)|[java/py/js](./algorithms/MinimumAddToMakeParenthesesValid)|Medium|
305306

306307
# Database
307308
|#|Title|Solution|Difficulty|
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
# Minimum Add To Make Parentheses Valid
2+
This problem is easy to solve by stack
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
class Solution {
2+
public int minAddToMakeValid(String S) {
3+
LinkedList<Character> stack = new LinkedList<Character>();
4+
5+
for (char c : S.toCharArray()) {
6+
if (c == ')' && stack.size() > 0 && stack.peek().equals('('))
7+
stack.pop();
8+
else
9+
stack.push(c);
10+
}
11+
12+
return stack.size();
13+
}
14+
}
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
/**
2+
* @param {string} S
3+
* @return {number}
4+
*/
5+
var minAddToMakeValid = function(S) {
6+
let stack = []
7+
8+
S.split('').forEach(c => {
9+
if (c == ')' && stack.length > 0 && stack[stack.length - 1] == '(')
10+
stack.pop()
11+
else
12+
stack.push(c)
13+
})
14+
return stack.length
15+
};
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
class Solution(object):
2+
def minAddToMakeValid(self, S):
3+
"""
4+
:type S: str
5+
:rtype: int
6+
"""
7+
stack = []
8+
9+
for c in S:
10+
if c == ')' and len(stack) > 0 and stack[-1] == '(':
11+
stack.pop()
12+
else:
13+
stack.append(c)
14+
15+
return len(stack)

0 commit comments

Comments
 (0)
0