-
Notifications
You must be signed in to change notification settings - Fork 0
/
BalancedParetheses_Matching1.java
74 lines (74 loc) · 1.45 KB
/
BalancedParetheses_Matching1.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
62
63
64
65
66
67
68
69
70
71
72
73
74
package rank;
import java.util.*;
public class BalancedParetheses_Matching1
{
public static void main(String args[])
{
BalancedParetheses_Matching1 b=new BalancedParetheses_Matching1();
Scanner sc=new Scanner(System.in);
System.out.println("Enter The Number Of String - ");
int n=sc.nextInt();
String s[]=new String[n];
for(int i=0;i<n;i++)
{
s[i]=sc.next();
}
String ss[]=new String[n];
ss=b.CheckParentheses1(s);
for(int i=0;i<n;i++)
{
System.out.println(ss[i]);
}
}
public String[] CheckParentheses1(String s[])throws EmptyStackException
{
String ss[]=new String[s.length];
for(int i=0;i<s.length;i++)
{
Stack<Character> st=new Stack();
for(int j=0;j<s[i].length();j++)
{
if(s[i].charAt(j)=='{' || s[i].charAt(j)=='[' || s[i].charAt(j)=='(')
{
st.push(s[i].charAt(j));
}
if(st.isEmpty())
{
ss[i]="NO";
}
switch(s[i].charAt(j))
{
case ')':
{
if(st.peek()=='{' || st.peek()=='[')
{
ss[i]="NO";
}
st.pop();
break;
}
case '}':
{
if(st.peek()=='(' || st.peek()=='[')
{
ss[i]="NO";
}
st.pop();
break;
}
case ']':
{
if(st.peek()=='(' || st.peek()=='{')
{
ss[i]="NO";
}
st.pop();
break;
}
}
ss[i]=(st.isEmpty())?"YES":"NO";
}
}
return ss;
}
}