-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy path443. String Compression.js
81 lines (72 loc) · 1.6 KB
/
443. String Compression.js
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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
/*
443. String Compression
https://leetcode.com/problems/string-compression/
*/
/**
* @param {character[]} chars
* @return {number}
*/
/*
Input:
["a"]
Output:
[]
Expected:
["a"]
Input:
["a","a","a","b","b","a","a"]
Output:
["a","5","b","2"]
Expected:
["a","3","b","2","a","2"]
Input:
["a","b","b","b","b","b","b","b","b","b","b","b","b"]
Output:
["a","b","12"]
Expected:
["a","b","1","2"]
*/
var compress = function (chars) {
if (chars.length == 1) {
return chars.length;
}
var currentValue = chars[0];
var count = 1;
var arr = [];
for (let i = 1; i < chars.length; i++) {
if (currentValue === chars[i]) {
count++;
} else {
arr.push(currentValue);
if (count > 9) {
`${count}`.split("").map((value) => {
arr.push(value);
});
} else {
if (count != 1) {
arr.push(count.toString());
}
}
currentValue = chars[i];
count = 1;
}
if (i == chars.length - 1) {
arr.push(currentValue);
if (count > 9) {
`${count}`.split("").map((value) => {
arr.push(value);
});
} else {
if (count != 1) {
arr.push(count.toString());
}
}
}
}
chars.splice(0);
for (let i = 0; i < arr.length; i++) {
chars.push(arr[i]);
}
return chars;
};
console.log(compress(["a", "b", "b", "b", "c", "c", "a", "a", "a"]));