-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathbalancedString.cpp
More file actions
100 lines (89 loc) · 1.68 KB
/
balancedString.cpp
File metadata and controls
100 lines (89 loc) · 1.68 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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
/*
Consider the balanced parentheses problem.
You have a bracket sequence made up of opening '(' and closing ')' parentheses.
You must check if this bracket sequence is balanced.
A bracket sequence is considered balanced if for every prefix of the sequence,
the number of opening brackets is greater than or equal
to the number of closing brackets, and the total number of opening brackets is equal to the number of closing brackets.
Source: Hackerearth
*/
#include<iostream>
using namespace std;
int top=-1;
int check(string str,char stack[],int len);
int stackSize();
int push(char stack[],char item,int len);
int pop();
int main()
{
string str;
cout<<"Enter the string: \n";
cin>>str;
int len = str.length();
char stack[len];
if (check(str,stack,len))
{
cout<<"String is balanced";
}
else
{
cout<<"String is unbalanced";
}
return 0;
}
int push(char stack[],char item,int len)
{
if(top==len-1)
{
return 1;
}
else
{
top++;
stack[top]=item;
return 0;
}
}
int pop()
{
if(top==-1)
{
return 1;
}
else
{
top--;
return 0;
}
}
int stackSize()
{
return top+1;
}
int check(string str,char stack[],int len)
{ int flag=0;
for(int i=0;i<len;i++)
{
if(str[i]=='(')
{
if(push(stack,'(',len))
{
flag=1;
break;
}
}
else if(str[i]==')')
{
if(pop())
{
flag=1;
break;
}
}
}
if(stackSize()==0 && flag==0)
{
return 1;
}
return 0;
}