-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBalance_paranthesis.java
More file actions
98 lines (91 loc) · 2.2 KB
/
Copy pathBalance_paranthesis.java
File metadata and controls
98 lines (91 loc) · 2.2 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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
import java.util.*;
import java.io.*;
public class Balance_paranthesis
{
static class stack
{
int top=-1;
char items[] = new char[100];
void push(char x)
{
if (top == 99)
{
System.out.println("Stack full");
}
else
{
items[++top] = x;
}
}
char pop()
{
if (top == -1)
{
System.out.println("Underflow error");
return '\0';
}
else
{
char element = items[top];
top--;
return element;
}
}
boolean isEmpty()
{
if(top == -1)
{
return true;
}
else
return false;
}
}
static boolean isMatchingPair(char character1, char character2)
{
if (character1 == '(' && character2 == ')')
return true;
else if (character1 == '{' && character2 == '}')
return true;
else if (character1 == '[' && character2 == ']')
return true;
else
return false;
}
static boolean areParenthesisBalanced(String exp)
{
stack st=new stack();
for(int i=0;i<exp.length();i++)
{
char s = exp.charAt(i);
if (s == '{' || s == '(' || s == '[')
st.push(s);
if (s== '}' || s== ')' || s== ']')
{
if (st.isEmpty())
{
return false;
}
else if ( !isMatchingPair(st.pop(), s) )
{
return false;
}
}
}
if (st.isEmpty())
return true;
else
{
return false;
}
}
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
String exp= sc.next();
if (areParenthesisBalanced(exp))
System.out.println("Balanced ");
else
System.out.println("Not Balanced ");
}
}