File tree 2 files changed +57
-0
lines changed
2 files changed +57
-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
+ // FIND BALANCED PARENTHESIS
2
+ // FOR '[{()}]' ---->>>> BALANCED
3
+ // FOR '[{()]' ---->>>> UNBALANCED
4
+ // Time complexity : O(n) n is the length of the string provided.
5
+
6
+
7
+ function parentheses ( s ) {
8
+ if ( typeof s !== "string" || s . length % 2 !== 0 ) return false ;
9
+ let i = 0 ;
10
+ let arr = [ ] ;
11
+ while ( i < s . length ) {
12
+ if ( s [ i ] === "{" || s [ i ] === "(" || s [ i ] === "[" ) {
13
+ arr . push ( s [ i ] ) ;
14
+ }
15
+ else if ( s [ i ] === "}" && arr [ arr . length - 1 ] === "{" ) {
16
+ arr . pop ( ) ;
17
+ }
18
+ else if ( s [ i ] === ")" && arr [ arr . length - 1 ] === "(" ) {
19
+ arr . pop ( ) ;
20
+ }
21
+ else if ( s [ i ] === "]" && arr [ arr . length - 1 ] === "[" ) {
22
+ arr . pop ( ) ;
23
+ }
24
+ return "Unbalanced" ;
25
+
26
+ i ++
27
+ }
28
+ if ( arr . length === 0 )
29
+ return "Balanced" ;
30
+ } ;
31
+
32
+
33
+
34
+ module . exports = {
35
+ parentheses,
36
+ } ;
You can’t perform that action at this time.
0 commit comments