-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbraces.java
46 lines (35 loc) · 1.17 KB
/
braces.java
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
/* Write a program to validate if the input string has redundant braces?
Return 0/1
0 -> NO
1 -> YES
Input will be always a valid expression
and operators allowed are only + , * , - , /
Example:
((a + b)) has redundant braces so answer will be 1
(a + (a + b)) doesn't have have any redundant braces so answer will be 0
*/
public int braces(String a) {
if(a.isEmpty() || a==null)
return 0;
Stack<Character> stack = new Stack<Character>() ;
int i=0;
while(i< a.length())
{
if(a.charAt(i)== '('||a.charAt(i)== '+'|| a.charAt(i)== '*'|| a.charAt(i)== '-'|| a.charAt(i)== '/') {
stack.push(a.charAt(i));
}
else if(a.charAt(i)==')')
{
if(stack.peek()=='(')
return 1;
else
{
while(!stack.isEmpty() && stack.peek()!='(' )
stack.pop();
stack.pop();
}
}
i++;
}
return 0;
}