File tree Expand file tree Collapse file tree 3 files changed +22
-37
lines changed
solution/1600-1699/1653.Minimum Deletions to Make String Balanced Expand file tree Collapse file tree 3 files changed +22
-37
lines changed Original file line number Diff line number Diff line change @@ -422,19 +422,14 @@ func minimumDeletions(s string) int {
422
422
423
423
``` ts
424
424
function minimumDeletions(s : string ): number {
425
- let lb = 0 ,
426
- ra = 0 ;
427
- const n = s .length ;
428
- for (let i = 0 ; i < n ; ++ i ) {
429
- if (s .charAt (i ) === ' a' ) {
430
- ++ ra ;
431
- }
432
- }
433
- let ans = n ;
434
- for (let i = 0 ; i < n ; ++ i ) {
435
- ra -= s .charAt (i ) === ' a' ? 1 : 0 ;
425
+ let ra = [... s ].reduce ((acc , x ) => (x === ' a' ? acc + 1 : acc ), 0 );
426
+ let lb = 0 ;
427
+
428
+ let ans = s .length ;
429
+ for (const ch of s ) {
430
+ if (ch === ' a' ) ra -- ;
436
431
ans = Math .min (ans , lb + ra );
437
- lb += s . charAt ( i ) === ' b' ? 1 : 0 ;
432
+ if ( ch === ' b' ) lb ++ ;
438
433
}
439
434
return ans ;
440
435
}
Original file line number Diff line number Diff line change @@ -336,7 +336,7 @@ var minimumDeletions = function (s) {
336
336
337
337
<!-- solution: start -->
338
338
339
- ### Solution 3
339
+ ### Solution 3: Two-Variable Method
340
340
341
341
<!-- tabs: start -->
342
342
@@ -420,19 +420,14 @@ func minimumDeletions(s string) int {
420
420
421
421
``` ts
422
422
function minimumDeletions(s : string ): number {
423
- let lb = 0 ,
424
- ra = 0 ;
425
- const n = s .length ;
426
- for (let i = 0 ; i < n ; ++ i ) {
427
- if (s .charAt (i ) === ' a' ) {
428
- ++ ra ;
429
- }
430
- }
431
- let ans = n ;
432
- for (let i = 0 ; i < n ; ++ i ) {
433
- ra -= s .charAt (i ) === ' a' ? 1 : 0 ;
423
+ let ra = [... s ].reduce ((acc , x ) => (x === ' a' ? acc + 1 : acc ), 0 );
424
+ let lb = 0 ;
425
+
426
+ let ans = s .length ;
427
+ for (const ch of s ) {
428
+ if (ch === ' a' ) ra -- ;
434
429
ans = Math .min (ans , lb + ra );
435
- lb += s . charAt ( i ) === ' b' ? 1 : 0 ;
430
+ if ( ch === ' b' ) lb ++ ;
436
431
}
437
432
return ans ;
438
433
}
Original file line number Diff line number Diff line change 1
1
function minimumDeletions ( s : string ) : number {
2
- let lb = 0 ,
3
- ra = 0 ;
4
- const n = s . length ;
5
- for ( let i = 0 ; i < n ; ++ i ) {
6
- if ( s . charAt ( i ) === 'a' ) {
7
- ++ ra ;
8
- }
9
- }
10
- let ans = n ;
11
- for ( let i = 0 ; i < n ; ++ i ) {
12
- ra -= s . charAt ( i ) === 'a' ? 1 : 0 ;
2
+ let ra = [ ...s ] . reduce ( ( acc , x ) => ( x === 'a' ? acc + 1 : acc ) , 0 ) ;
3
+ let lb = 0 ;
4
+
5
+ let ans = s . length ;
6
+ for ( const ch of s ) {
7
+ if ( ch === 'a' ) ra -- ;
13
8
ans = Math . min ( ans , lb + ra ) ;
14
- lb += s . charAt ( i ) === 'b' ? 1 : 0 ;
9
+ if ( ch === 'b' ) lb ++ ;
15
10
}
16
11
return ans ;
17
12
}
You can’t perform that action at this time.
0 commit comments