File tree 2 files changed +51
-0
lines changed
2 files changed +51
-0
lines changed Original file line number Diff line number Diff line change
1
+ const { parentheses } = require ( '.' ) ;
2
+
3
+ describe ( 'Parentheses' , ( ) => {
4
+ it ( 'Should return true only when matching brackets are there' , ( ) => {
5
+ expect ( parentheses ( "{[()]})" ) . toEqual ( 'Balanced' ) ;
6
+ } ) ;
7
+
8
+ it ( 'Should return false when matching brackets are not there' , ( ) => {
9
+ expect ( parentheses ( "{[()}])" ) . toEqual ( 'UnBalanced' ) ;
10
+ } ) ;
11
+ it ( 'Should return true only when matching brackets are there' , ( ) => {
12
+ expect ( parentheses ( "{()})" ) . toEqual ( 'Balanced' ) ;
13
+ } ) ;
14
+
15
+ it ( 'Should return false when matching brackets are not there' , ( ) => {
16
+ expect ( parentheses ( "{[}])" ) . toEqual ( 'UnBalanced' ) ;
17
+ } ) ;
18
+
19
+
20
+
21
+ } ) ;
Original file line number Diff line number Diff line change
1
+ function parentheses ( s ) {
2
+ if ( typeof s !== "string" || s . length % 2 !== 0 ) return false ;
3
+ let i = 0 ;
4
+ let arr = [ ] ;
5
+ while ( i < s . length ) {
6
+ if ( s [ i ] === "{" || s [ i ] === "(" || s [ i ] === "[" ) {
7
+ arr . push ( s [ i ] ) ;
8
+ }
9
+ else if ( s [ i ] === "}" && arr [ arr . length - 1 ] === "{" ) {
10
+ arr . pop ( ) ;
11
+ }
12
+ else if ( s [ i ] === ")" && arr [ arr . length - 1 ] === "(" ) {
13
+ arr . pop ( ) ;
14
+ }
15
+ else if ( s [ i ] === "]" && arr [ arr . length - 1 ] === "[" ) {
16
+ arr . pop ( ) ;
17
+ }
18
+ return "Unbalanced" ;
19
+
20
+ i ++
21
+ }
22
+ if ( arr . length === 0 )
23
+ return "Balanced" ;
24
+ } ;
25
+
26
+
27
+
28
+ module . exports = {
29
+ parentheses,
30
+ } ;
You can’t perform that action at this time.
0 commit comments