-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStack_collections.java
More file actions
59 lines (55 loc) · 1.66 KB
/
Stack_collections.java
File metadata and controls
59 lines (55 loc) · 1.66 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
import java.util.*;
class Solution{
public static void main(String []argh)
{
Scanner sc = new Scanner(System.in);
while (sc.hasNext()) {
String input=sc.next();
//Complete the code
System.out.println(balanced(input));
}
}
public static boolean balanced(String input)
{
if(input.isEmpty())
{
return true;
}
else
{
//we will use stack..
Stack<Character> stack = new Stack<Character>(); //declareing stack..
int i;
for(i=0;i<input.length();i++) //traversing through the string..
{
char ch = input.charAt(i); //extracting th character..
if(ch=='('||ch=='{'||ch=='[') //if it is opening braces(push in the stack)
{
stack.push(ch);
}
else if(ch==']') //closing brace
{
if(stack.isEmpty() || stack.pop()!='[') //here we are actually poping the element from the stack..
{
return false;
}
}
else if(ch=='}')
{
if(stack.isEmpty() || stack.pop()!='{')
{
return false;
}
}
else if(ch==')')
{
if(stack.isEmpty() || stack.pop()!='(') //here popping of braces taking place...
{
return false;
}
}
}
return stack.isEmpty(); //at last if the stack is empty then it is balanced otherwise it is not..
}
}
}