921. Minimum Add to Make Parentheses Valid

Given a string S of '(' and ')' parentheses, we add the minimum number of parentheses ( '(' or ')', and in any positions ) so that the resulting parentheses string is valid.

Formally, a parentheses string is valid if and only if:

  • It is the empty string, or
  • It can be written as AB (A concatenated with B), where A and B are valid strings, or
  • It can be written as (A), where A is a valid string.

Given a parentheses string, return the minimum number of parentheses we must add to make the resulting string valid.

 

Example 1:

Input: "())"
Output: 1

Example 2:

Input: "((("
Output: 3

Example 3:

Input: "()"
Output: 0

Example 4:

Input: "()))(("
Output: 4
 1 class Solution {
 2     public int minAddToMakeValid(String s) {
 3         Stack<Character> stack = new Stack<>();
 4         char[] chs = s.toCharArray();
 5         for (char ch: chs) {
 6             if (ch == '(') {
 7                 stack.push(ch);
 8             } else {
 9                 if (!stack.isEmpty() && stack.peek() == '(') {
10                     stack.pop();
11                 } else {
12                     stack.push(')');
13                 }
14             }
15         }
16         return stack.size();
17     }
18     public int minAddToMakeValid(String S) {
19         int left = 0, right = 0;
20         for (int i = 0; i < S.length(); ++i) {
21             if (S.charAt(i) == '(') {
22                 left++;
23             } else if (left > 0) {
24                 left--;
25             } else {
26                 right++;
27             }
28         }
29         return left + right;
30     }
31 }

这题也可以问 最少需要删除的bracket, 答案是一样的。

posted @ 2021-03-29 05:13  北叶青藤  阅读(41)  评论(0)    收藏  举报