File tree 1 file changed +19
-39
lines changed
scripts/algorithms/M/Minimum Insertions to Balance a Parentheses String
1 file changed +19
-39
lines changed Original file line number Diff line number Diff line change
1
+ // Runtime: 34 ms (Top 32.51%) | Memory: 13.40 MB (Top 25.91%)
2
+
1
3
class Solution {
2
4
public:
3
5
int minInsertions (string s) {
4
- stack<int > st ;
5
- int n = s. size () ;
6
- int insert = 0 ;
7
- for ( int i = 0 ; i < n; i++)
8
- {
9
- if (s[i] == ' ( ' )
10
- {
11
- if (st. empty ())
12
- {
13
- st. push ( 2 );
6
+ stack<char > v ;
7
+ int ans = 0 ;
8
+ for ( int i = 0 ;i < s. size ();i++){
9
+ if (s[i] == ' ( ' ) v. push (s[i]);
10
+ else {
11
+ if (s[i] == ' ) ' && i < s. size () && s[i + 1 ] == ' ) ' ) {
12
+ if (!v. empty ())
13
+ v. pop ();
14
+ else ans++;
15
+ i++; // because we considered i+1 in this case
14
16
}
15
- else
16
- {
17
- if (st.top () != 2 )
18
- {
19
- st.pop ();
20
- insert++;
17
+ else if (s[i] == ' )' && i < s.size () && s[i + 1 ] != ' )' ){
18
+ if (!v.empty ()){
19
+ v.pop ();
20
+ ans++;
21
21
}
22
- st. push ( 2 ) ;
22
+ else ans += 2 ;
23
23
}
24
24
}
25
- else
26
- {
27
- if (st.empty ())
28
- {
29
- insert++;
30
- st.push (1 );
31
- }
32
- else
33
- {
34
- int dummy = st.top ();
35
- st.pop ();
36
- dummy--;
37
- if (dummy)
38
- st.push (dummy);
39
- }
40
- }
41
- }
42
- while (!st.empty ())
43
- {
44
- insert += st.top ();
45
- st.pop ();
46
25
}
47
- return insert;
26
+ if (v.empty ()) return ans;
27
+ return v.size ()*2 + ans;
48
28
}
49
29
};
You can’t perform that action at this time.
0 commit comments