Skip to content

Commit eca15ef

Browse files
authored
Create Stack-Check redundant brackets
1 parent 843d28e commit eca15ef

File tree

1 file changed

+63
-0
lines changed

1 file changed

+63
-0
lines changed

Stack-Check redundant brackets

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
For a given expression in the form of a string, find if there exist any redundant brackets or not. It is given that the expression contains only rounded brackets or parenthesis and the input expression will always be balanced.
2+
A pair of the bracket is said to be redundant when a sub-expression is surrounded by unnecessary or needless brackets.
3+
Example:
4+
Expression: (a+b)+c
5+
Since there are no needless brackets, hence, the output must be 'false'.
6+
7+
Expression: ((a+b))
8+
The expression can be reduced to (a+b). Hence the expression has redundant brackets and the output will be 'true'.
9+
Note:
10+
You will not get a partial score for this problem. You will get marks only if all the test cases are passed.
11+
Input Format :
12+
The first and the only line of input contains a string expression, without any spaces in between.
13+
Output Format :
14+
The first and the only line of output will print either 'true' or 'false'(without the quotes) denoting whether the input expression contains redundant brackets or not.
15+
Note:
16+
You are not required to print the expected result. It has already been taken care of.
17+
Constraints:
18+
0 <= N <= 10^6
19+
Where N is the length of the expression.
20+
21+
Time Limit: 1 second
22+
Sample Input 1:
23+
a+(b)+c
24+
Sample Output 1:
25+
true
26+
Explanation:
27+
The expression can be reduced to a+b+c. Hence, the brackets are redundant.
28+
Sample Input 2:
29+
(a+b)
30+
Sample Output 2:
31+
false
32+
33+
***********************************Code************************************
34+
import java.util.Stack;
35+
36+
public static boolean checkRedundantBrackets(String expression) {
37+
38+
Stack<Character> stack=new Stack<Character>();
39+
int count=0;
40+
for(int i=0;i<expression.length();i++)
41+
{
42+
char c=expression.charAt(i);
43+
if (c==')')
44+
{
45+
while(!stack.isEmpty() && stack.peek()!='(')
46+
{
47+
count=count+1;
48+
stack.pop();
49+
}
50+
if (count==0 || count==1)
51+
{
52+
return true;
53+
}
54+
stack.pop();
55+
count=0;
56+
}
57+
else
58+
{
59+
stack.push(c);
60+
}
61+
}
62+
return false;
63+
}

0 commit comments

Comments
 (0)