-
Notifications
You must be signed in to change notification settings - Fork 321
Expand file tree
/
Copy pathch1-q6.js
More file actions
33 lines (30 loc) · 883 Bytes
/
ch1-q6.js
File metadata and controls
33 lines (30 loc) · 883 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
'use strict';
/**
* Takes an input string and counts contiguous sequences of the same character
* and replaces them with XC (X = count, C = character).
*
* N = |str|
* Time: O(N)
* Additional space: O(N)
*
* @param {string} str [description]
* @return {[type]} [description]
*/
export function compressString(str) {
if (!str) {
return str;
}
let cStr = '';
for (let i = 0; i < str.length; ++i) {
let char = str[i],
start = i;
while (i + 1 < str.length && char === str[i + 1]) {
++i;
}
// JS does not have a StringBuilder/StringBuffer style class for creating strings
// string concatenation has been heavily optimised in JS implementations and
// is faster than creating a string via an array then using a .join('') at the end
cStr += char + (i - start + 1);
}
return cStr.length < str.length ? cStr : str;
}