-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDemo.java
79 lines (67 loc) · 1.75 KB
/
Demo.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
75
76
77
78
79
/*
Copyright (C) Deepali Srivastava - All Rights Reserved
This code is part of DSA course available on CourseGalaxy.com
*/
package parentheses;
import java.util.Scanner;
public class Demo
{
public static void main(String[] args)
{
String expression;
Scanner scan = new Scanner(System.in);
System.out.print("Enter an expression with parentheses : ");
expression = scan.nextLine();
if(isValid(expression))
System.out.println("Valid expression");
else
System.out.println("Invalid expression");
scan.close();
}
public static boolean isValid(String expr)
{
StackA st = new StackA();
char ch;
for(int i=0; i<expr.length(); i++)
{
if(expr.charAt(i)=='(' || expr.charAt(i)=='{' || expr.charAt(i)=='[')
st.push(expr.charAt(i));
if(expr.charAt(i)==')' || expr.charAt(i)=='}' || expr.charAt(i)==']')
if(st.isEmpty())
{
System.out.println("Right parentheses are more than left parentheses");
return false;
}
else
{
ch=st.pop();
if(!matchParentheses(ch,expr.charAt(i)))
{
System.out.println("Mismatched parentheses are : ");
System.out.println(ch + " and " + expr.charAt(i));
return false;
}
}
}
if(st.isEmpty())
{
System.out.println("Balanced Parentheses");
return true;
}
else
{
System.out.println("Left parentheses are more than right parentheses");
return false;
}
}
public static boolean matchParentheses(char leftPar,char rightPar)
{
if(leftPar=='[' && rightPar==']')
return true;
if(leftPar=='{' && rightPar=='}')
return true;
if(leftPar=='(' && rightPar==')')
return true;
return false;
}
}