-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathParantheses.java
More file actions
53 lines (46 loc) · 954 Bytes
/
Parantheses.java
File metadata and controls
53 lines (46 loc) · 954 Bytes
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
/*
https://www.hackerrank.com/challenges/java-stack
*/
import java.util.*;
public class Main{
public static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
while(input.hasNext()){
String str = input.next();
System.out.println(isBalanced(str));
}
}
public static boolean isBalanced(String str){
Stack<Character> stack = new Stack<>();
for(int i=0;i<str.length();i++){
char c = str.charAt(i);
if(c=='(' || c=='{' || c=='[')
stack.push(c);
else{
if(stack.isEmpty())
return false;
switch(c){
case ')':
if(stack.peek()=='(')
stack.pop();
else
return false;
break;
case ']':
if(stack.peek()=='[')
stack.pop();
else
return false;
break;
case '}':
if(stack.peek()=='{')
stack.pop();
else
return false;
break;
}
}
}
return stack.isEmpty();
}
}