Skip to content

Commit 127f098

Browse files
authored
Merge pull request #800 from ishikasinha-d/redundant-braces
Create redundant_braces.cpp
2 parents 4c358cb + 5ede788 commit 127f098

File tree

1 file changed

+69
-0
lines changed

1 file changed

+69
-0
lines changed
Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
// Given a string A of length n denoting an expression. It contains the following operators ’+’, ‘-‘, ‘*’, ‘/’.
2+
// Check whether A has redundant braces or not.
3+
4+
#include <bits/stdc++.h>
5+
using namespace std;
6+
7+
int redundantBraces(string A) {
8+
9+
int n= A.length();
10+
stack <char> s;
11+
12+
for(int i=0; i< n; i++)
13+
{
14+
//we'll push the operators and opening braces in the stack
15+
if(A[i]=='+' || A[i]=='-'|| A[i]=='/'|| A[i]=='*' || A[i]=='(' )
16+
s.push(A[i]);
17+
18+
//when we encounter closing braces, we need to start popping
19+
if(A[i]==')')
20+
{
21+
//if there are no operators, it means we have redundant braces for eg. ()
22+
if(s.top()=='(')
23+
return 1;
24+
25+
//else we start popping till we encounter opening braces
26+
//count variable will keep count of number of operators enclosed within the braces
27+
int count=0;
28+
while(!s.empty() && s.top()!='(')
29+
{
30+
s.pop();
31+
count++;
32+
}
33+
//count=0 means we have something like (a) which has redundant braces
34+
if(count==0)
35+
return 1;
36+
s.pop();
37+
}
38+
}
39+
40+
return 0;
41+
}
42+
43+
int main()
44+
{
45+
string str;
46+
cin>>str;
47+
if(redundantBraces(str))
48+
cout<<str+" has redundant braces";
49+
else
50+
cout<<str+" doesn't have any redundant braces";
51+
return 0;
52+
53+
}
54+
55+
// Test Cases
56+
// Input 1:
57+
// A = "((a + b))"
58+
// Output 1:
59+
// 1
60+
// Explanation 1:
61+
// ((a + b)) has redundant braces so answer will be 1.
62+
// Input 2:
63+
// A = "(a + (a + b))"
64+
// Output 2:
65+
// 0
66+
// Explanation 2:
67+
// (a + (a + b)) doesn't have have any redundant braces so answer will be 0.
68+
69+
// Time complexity: O(n)

0 commit comments

Comments
 (0)