-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathRedundantBraces.java
More file actions
81 lines (56 loc) · 1.65 KB
/
RedundantBraces.java
File metadata and controls
81 lines (56 loc) · 1.65 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
/**
Given a string A denoting an expression. It contains the following operators ’+’, ‘-‘, ‘*’, ‘/’.
Chech whether A has redundant braces or not.
Return 1 if A has redundant braces, else return 0.
Note: A will be always a valid expression.
Input Format
The only argument given is string A.
Output Format
Return 1 if string has redundant braces, else return 0.
For Example
Input 1:
A = "((a + b))"
Output 1:
1
Explanation 1:
((a + b)) has redundant braces so answer will be 1.
Input 2:
A = "(a + (a + b))"
Output 2:
0
Explanation 2:
(a + (a + b)) doesn't have have any redundant braces so answer will be 0.
**/
public class Solution {
public int braces(String A) {
Stack<Character> stack = new Stack<Character>();
char[] str = A.toCharArray();
for(char ch : str)
{
if(ch == ')')
{
char top = stack.peek();
stack.pop();
boolean isRedundant = true;
while(top != '(')
{
if(top == '+' || top == '-' || top == '*' || top == '/')
{
isRedundant = false;
}
top = stack.peek();
stack.pop();
}
if(isRedundant == true)
{
return 1;
}
}
else
{
stack.push(ch);
}
}
return 0;
}
}