File tree Expand file tree Collapse file tree 1 file changed +62
-0
lines changed Expand file tree Collapse file tree 1 file changed +62
-0
lines changed Original file line number Diff line number Diff line change
1
+ import java .util .*;
2
+ import java .io .*;
3
+ import java .lang .*;
4
+
5
+ class BalancedParenthesis {
6
+ public static void main (String args []){
7
+ Scanner scan = new Scanner (System .in );
8
+
9
+ //Reading total number of testcases
10
+ int t = scan .nextInt ();
11
+ while (t -->0 ){
12
+ //reading the string
13
+ String str = scan .next ();
14
+
15
+ //calling ispar() of Parenthesis class and printing "balanced" if it returns true else print "not balanced"
16
+ if (new Solution ().ispar (str ) == true )
17
+ System .out .println ("balanced" );
18
+ else
19
+ System .out .println ("not balanced" );
20
+ }
21
+ }
22
+ }
23
+
24
+ class Solution {
25
+ //Function to check if brackets are balanced or not.
26
+ static boolean ispar (String str ){
27
+
28
+ //if string is null or the length of string is not even then string is not balanced.
29
+ if (str == null || ((str .length () % 2 ) != 0 )) {
30
+ return false ;
31
+ }
32
+ else {
33
+ //if string entered is other than parenthesis, return false.
34
+ char [] ch = str .toCharArray ();
35
+ for (char c : ch ) {
36
+ if (!(c == '{' || c == '[' || c == '(' || c == '}' || c == ']' || c == ')' )) {
37
+ return false ;
38
+ }
39
+
40
+ }
41
+ }
42
+
43
+ Deque <Character > deque = new LinkedList <>();
44
+ //peekFirst() is used to retrieve or fetch the first element of the deque.
45
+
46
+ for (char ch : str .toCharArray ()) {
47
+ if (ch == '{' || ch == '[' || ch == '(' ) {
48
+ deque .addFirst (ch );
49
+ }
50
+ else {
51
+ if (!deque .isEmpty () && ((deque .peekFirst () == '{' && ch == '}' ) || (deque .peekFirst () == '[' && ch == ']' ) || (deque .peekFirst () == '(' && ch == ')' ))) {
52
+ deque .removeFirst ();
53
+ }
54
+ else
55
+ return false ;
56
+ }
57
+ }
58
+
59
+ return true ;
60
+ }
61
+ }
62
+
You can’t perform that action at this time.
0 commit comments