-
Notifications
You must be signed in to change notification settings - Fork 30
Expand file tree
/
Copy pathCode : Balanced Parenthesis
More file actions
65 lines (59 loc) · 1.45 KB
/
Code : Balanced Parenthesis
File metadata and controls
65 lines (59 loc) · 1.45 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
// Code : Balanced Parenthesis
// Send Feedback
// Given a string expression, check if brackets present in the expression are balanced or not. Brackets are balanced if the bracket which opens last, closes first.
// You need to return true if it is balanced, false otherwise.
// Note: This problem was asked in initial rounds in Facebook
// Sample Input 1 :
// { a + [ b+ (c + d)] + (e + f) }
// Sample Output 1 :
// true
// Sample Input 2 :
// { a + [ b - c } ]
// Sample Output 2 :
// false
import java.util.*;
public class Solution {
public static boolean matchingPeer(char open , char close){
if ( open == '(' && close == ')'){
return true;
}
if ( open == '[' && close == ']'){
return true;
}
if ( open == '{' && close == '}'){
return true;
}
// you can add more open and close rule
else{
return false;
}
}
public static boolean checkBalanced(String equation)
{
// Write your code here
char[] c = equation.toCharArray();
Stack <Character> myStack= new Stack <Character> ();
for (int i = 0; i < c.length; i++)
{
if(c[i]=='(' || c[i] == '[' || c[i] == '{'){
myStack.push(c[i]);
continue;
}
else if (c[i]== ')' || c[i]==']' || c[i] == '}'){
if(myStack.isEmpty())
return false;
if(matchingPeer(myStack.peek(),c[i]) == true){
myStack.pop();
} else {
return false;
}
}
}
if(myStack.isEmpty()){
return true;
}
else {
return false;
}
}
}