leetcode-921 Minimum Add to Make Parentheses Valid

921. Minimum Add to Make Parentheses Valid

Description

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:

1
2
Input: "())"
Output: 1

Example 2:

1
2
Input: "((("
Output: 3

Example 3:

1
2
Input: "()"
Output: 0

Example 4:

1
2
Input: "()))(("
Output: 4

Note:

  1. S.length <= 1000
  2. S only consists of ‘(‘ and ‘)’ characters.

Analyse

找出能使括号字符串合法的最小括号数

用栈当然可以搞定,看最后栈里剩下的元素个数就是要求的数

直接遍历一遍字符串,数()的个数,最开始我的做法是直接)的个数-(的个数,仔细一想不对,()))((这个用例就通不过,括号的顺序很重要

从左到右遍历字符串

  1. 遇到(就计数器+1
  2. 遇到),如果之前还有(就直接消去一个(,否则就要增加一个(来抵消这个)

Code

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
int minAddToMakeValid(string S)
{
int left_count = 0;
int total = 0;

for(char c : S)
{
if (c == '(')
{
++left_count;
++total;
}
else
{
if (left_count > 0)
{
--left_count;
--total;
}
else
{
++total;
}
}
}

return total;
}

Result

4ms faster than 100.00%

Others

吐槽下改版后LeetCode的界面真难看,三层额头,看题的空间都变小了