-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathminimumEditsParanthesis.java
More file actions
55 lines (44 loc) · 1.14 KB
/
minimumEditsParanthesis.java
File metadata and controls
55 lines (44 loc) · 1.14 KB
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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
class Solution {
public int minAddToMakeValid(String S) {
Stack<Character> stack = new Stack<Character>();
int count = 0;
for(int i = 0 ; i < S.length(); i++)
{
if(S.charAt(i) == '(')
stack.push(')');
else if(S.charAt(i) == '[')
stack.push(']');
else if(S.charAt(i)== '{')
stack.push('}');
else
{
if(stack.isEmpty()) count ++;
else if(!stack.isEmpty() && stack.pop() != S.charAt(i))
count ++;
}
}
while(!stack.isEmpty())
{
stack.pop();
count++;
}
return count;
}
}
///
/*
class Solution {
public int minAddToMakeValid(String S) {
int ans = 0, bal = 0;
for (int i = 0; i < S.length(); ++i) {
bal += S.charAt(i) == '(' ? 1 : -1;
// It is guaranteed bal >= -1
if (bal == -1) {
ans++;
bal++;
}
}
return ans + bal;
}
}
*/