-
Notifications
You must be signed in to change notification settings - Fork 0
/
Parenthesis_Checker.java
61 lines (57 loc) · 1.59 KB
/
Parenthesis_Checker.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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
import java.util.*;
/*Question: Parenthesis Checker.
Link:-https://practice.geeksforgeeks.org/problems/parenthesis-checker2744/1
Input: {([])}
Output: true
Explanation: { ( [ ] ) }. Same colored brackets can form balanced pairs, with 0 number of unbalanced bracket.
Input: ([]
Output: false
Explanation: ([]. Here square bracket is balanced but the small bracket is not balanced and Hence , the output will be unbalanced.
*/
public class Parenthesis_Checker {
static boolean ispar(String x)
{
// add your code here
Stack<Character> st=new Stack<>();
for(int i=0;i<x.length();i++){
if(st.isEmpty()){
st.push(x.charAt(i));
}
else if(x.charAt(i)==')'){
if(st.peek()!='('){
return false;
}
else{
st.pop();
}
}
else if(x.charAt(i)==']'){
if(st.peek()!='['){
return false;
}
else{
st.pop();
}
}
else if(x.charAt(i)=='}'){
if(st.peek()!='{'){
return false;
}
else{
st.pop();
}
}
else{
st.push(x.charAt(i));
}
}
if(st.isEmpty()){
return true;
}
return false;
}
public static void main(String[] args) {
String s="(({{[]}}))";
System.out.println(ispar(s));
}
}