-
Notifications
You must be signed in to change notification settings - Fork 294
Expand file tree
/
Copy pathstringCompression.js
More file actions
43 lines (33 loc) · 907 Bytes
/
stringCompression.js
File metadata and controls
43 lines (33 loc) · 907 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
/*
Write a function `compression` which takes a string as input and returns a compressed version of the string. The compression is done by replacing consecutive repeating characters with the character followed by the count of repetitions. If a character does not repeat, it is not followed by a count.
Example:
- Input: "aaabbbbcccvvmm"
- Output: "a3b4c3v2m2"
- Input: "abc"
- Output: "abc"
- Input: "aabbcc"
- Output: "a2b2c2"
- Input: ""
- Output: ""
Note:
- The function should work for any alphanumeric string.
Once you've implemented the logic, test your code by running
- `npm run test-compressString`
*/
function compression(s){
let n=s.length;
let cnt=0;
let ans="";
for(let i=0; i<n; i++){
cnt++;
if(s[i]!==s[i+1]){
ans+=s[i];
if(cnt>1){
ans+=cnt;
}
cnt=0;
}
}
return ans;
}
module.exports = compression;