-
Notifications
You must be signed in to change notification settings - Fork 0
/
java29.java
53 lines (50 loc) · 1.76 KB
/
java29.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
//hackkerank
//javastack ptoblem
//solution
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
import java.util.ArrayList;
public class JavaStack {
static boolean isBallanced(String paranString)
{
List<String>closingParan = Arrays.asList("}", ")", "]");
boolean isBallanced = true;
ArrayList<String> stack = new ArrayList<String>();
if(paranString.length()>0){
for(int i = 0;i<paranString.length();i++){
String paran = paranString.substring(i,i+1);
if(stack.size() == 0 && closingParan.contains(paran)){
isBallanced=false;
break;
}else{
if(paran.equals("{") || paran.equals("(") || paran.equals("[")){
stack.add(paran);
}else{
String stackParan = stack.get(stack.size()-1);
if((stackParan.equals("{") && paran.equals("}")) || (stackParan.equals("(") && paran.equals(")") || (stackParan.equals("[") && paran.equals("]")))) {
stack.remove(stack.size()-1);
}else{
isBallanced = false;
break;
}
}
}
}
}
if(stack.size()>0) isBallanced = false;
return isBallanced;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while(sc.hasNext()){
if(isBallanced(sc.nextLine())){
System.out.println("true");
}else{
System.out.println("false");
}
}
}
}