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