Skip to content

Commit 8497485

Browse files
committed
maximum size of balanced bracket sequence added
1 parent 8781c41 commit 8497485

File tree

1 file changed

+60
-0
lines changed

1 file changed

+60
-0
lines changed
Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
/*
2+
Given a sequence of brackets as a string, find maximum possible length of balanced bracket sequence.
3+
string consists only two characters , one is '(' another is ')'
4+
can be solved this with the help of stack data structure.
5+
*/
6+
7+
#include <bits/stdc++.h>
8+
using namespace std;
9+
10+
int balanced_bracket_sequence(string s, int string_size)
11+
{
12+
int max_possible_balanced_bracket_sequence = 0;
13+
stack < char > st;
14+
for(int i = 0 ; i < string_size; i++)
15+
{
16+
/* Here if the current character of string is ' ( ' we will push it to stack
17+
and if the current character of string is ' ) ' and
18+
stack is not empty we will pop from the top of the stack
19+
increment the max_possible_balanced_bracket_sequence by 2
20+
every time.
21+
*/
22+
if(s[i] == '(' )
23+
{
24+
st.push(s[i]);
25+
}
26+
else if(s[i]==')')
27+
{
28+
if(!st.empty())
29+
{
30+
if(st.top()=='(')
31+
{
32+
st.pop();
33+
max_possible_balanced_bracket_sequence += 2;
34+
}
35+
}
36+
}
37+
}
38+
return max_possible_balanced_bracket_sequence;
39+
}
40+
41+
int main()
42+
{
43+
cout << "Enter the string : \n";
44+
string s;
45+
cin >> s;
46+
int string_size = (int)s.size();
47+
int max_balanced_bracket_sequence = balanced_bracket_sequence(s, string_size);
48+
cout << "Maximum possible length of balanced bracket sequence is : \n";
49+
cout << max_balanced_bracket_sequence << endl;
50+
}
51+
52+
/*
53+
Input and Output
54+
Enter the string :
55+
((()())
56+
Maximum possible length of balanced bracket sequence is :
57+
6
58+
Time Complexity : O(N)
59+
Space Complexity : O(N)
60+
*/

0 commit comments

Comments
 (0)