-
Notifications
You must be signed in to change notification settings - Fork 0
/
MinimumInsertionstoBalanceaParenthesesString.java
62 lines (54 loc) · 1.58 KB
/
MinimumInsertionstoBalanceaParenthesesString.java
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
53
54
55
56
57
58
59
60
61
package stack;
import utils.LeetCode;
import utils.Level;
import java.util.Stack;
@LeetCode(no=1541,
url = "https://leetcode.com/problems/minimum-insertions-to-balance-a-parentheses-string/",
title = " Minimum Insertions to Balance a Parentheses String",
level = Level.MEDIUM)
public class MinimumInsertionstoBalanceaParenthesesString {
public int minInsertions(String s) {
char[] sChars= s.toCharArray();
int n= sChars.length;
int total=0;
Stack<Character> st= new Stack<>();
for(int i=0;i<sChars.length;i++){
char c= sChars[i];
if(c=='('){
st.push('(');
continue;
}
if(st.isEmpty()){
if(i<n-1){
char next= sChars[i+1];
if(c==next){
total++;
i+=1;
}else {
total+=2;
}
}else{
total+=2;
}
}else {
if(i<n-1){
char next= sChars[i+1];
if(c==next){
st.pop();
// total++;
i+=1;
}else {
st.pop();
total+=1;
}
}else{
st.pop();
total+=1;
}
}
}
if(!st.isEmpty())
total+=2*st.size();
return total;
}
}