File tree Expand file tree Collapse file tree 1 file changed +33
-0
lines changed
JavaScript/chapter01/1.6 - String Compression Expand file tree Collapse file tree 1 file changed +33
-0
lines changed Original file line number Diff line number Diff line change
1
+ /* Implement a method to perform basic string
2
+ compression using the counts of repeated characters
3
+ Ex: 'aabcccccaaa' would become a2b1c5a3
4
+ */
5
+
6
+ const stringCompression = ( str ) => {
7
+ if ( ! str . length ) {
8
+ return '' ;
9
+ }
10
+ var compStr = '' ;
11
+ var count = 1 ;
12
+ var currentChar = str [ 0 ] ;
13
+ for ( let i = 1 ; i < str . length ; i ++ ) {
14
+ let char = str [ i ] ;
15
+ if ( char === currentChar ) {
16
+ count ++ ;
17
+ if ( i === str . length - 1 ) {
18
+ compStr += `${ currentChar } ${ count } ` ;
19
+ }
20
+ } else {
21
+ compStr += `${ currentChar } ${ count } ` ;
22
+ currentChar = char ;
23
+ count = 1 ;
24
+ }
25
+ }
26
+ return compStr ;
27
+ }
28
+
29
+ // TESTS
30
+ console . log ( stringCompression ( 'aabcccccaaa' ) === 'a2b1c5a3' ) ;
31
+ console . log ( stringCompression ( 'cccccccc' ) === 'c8' ) ;
32
+ console . log ( stringCompression ( '' ) === '' ) ;
33
+ console . log ( stringCompression ( 'AabccCccaaa' ) === 'A1a1b1c2C1c2a3' ) ;
You can’t perform that action at this time.
0 commit comments