-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBalancedParenthesis.java
More file actions
58 lines (58 loc) · 1.38 KB
/
BalancedParenthesis.java
File metadata and controls
58 lines (58 loc) · 1.38 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
/* Create a program that checks if in a given String expression all the parenthesis are balanced
(Test) -> valid
(no() -> invalid
()(()) -> valid
(123(456)(7))( -> invalid
(val({}<(0)>lid)) -> valid
*/
import java.util.Stack;
import java.util.Scanner;
public class BalancedParenthesis{
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
Stack<Character> s = new Stack<Character>();
System.out.println("Enter the expression!!");
String str = in.nextLine();
str = str.replaceAll("[A-Za-z0-9]", "");
for (int i=0;i<str.length() ;i++ ) {
if (str.charAt(i)=='('||str.charAt(i)=='{'||str.charAt(i)=='['||str.charAt(i)=='<') {
s.push(str.charAt(i));
}
else if(str.charAt(i)==')'){
if (s.peek()=='(') {
s.pop();
}else{
System.out.println("Invalid");
break;
}
}
else if(str.charAt(i)=='}'){
if (s.peek()=='{') {
s.pop();
}else{
System.out.println("Invalid");
break;
}
}else if(str.charAt(i)==']'){
if (s.peek()=='[') {
s.pop();
}else{
System.out.println("Invalid");
break;
}
}else if(str.charAt(i)=='>'){
if (s.peek()=='<') {
s.pop();
}else{
System.out.println("Invalid");
break;
}
}
}
if (s.isEmpty()) {
System.out.println("Valid");
}else{
System.out.println("Invalid");
}
}
}