-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBracketChecking.java
More file actions
42 lines (34 loc) · 1.14 KB
/
Copy pathBracketChecking.java
File metadata and controls
42 lines (34 loc) · 1.14 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
//Given strings of brackets, determine whether each sequence of brackets is balanced.
//If a string is balanced, print true on a new line; otherwise, print False on a new line.
import java.util.*;
public class BracketChecking{
public static boolean CheckParentesis(String str)
{
if (str.isEmpty()) //Empty String is considered as TRUE.
return true;
Stack<Character> stack = new Stack<Character>();
for (int i = 0; i < str.length(); i++)
{
char current = str.charAt(i);
if (current == '{' || current == '(' || current == '[')
{
stack.push(current);
}
if (current == '}' || current == ')' || current == ']')
{
if (stack.isEmpty())
return false;
char last = stack.peek();
if (current == '}' && last == '{' || current == ')' && last == '(' || current == ']' && last == '[')
stack.pop();
else
return false;
}
}
return stack.isEmpty();
}
public static void main(String[] args) {
String str = "({})";
System.out.println(CheckParentesis(str));
}
}