-
Notifications
You must be signed in to change notification settings - Fork 44
/
Problem29.js
86 lines (72 loc) · 1.88 KB
/
Problem29.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
82
83
84
85
86
// Problem 29
//
// This problem was asked by Amazon.
//
// Run-length encoding is a fast and simple method of encoding strings. The basic idea is to represent repeated successive characters as a single count and character.
//
// For example, the string "AAAABBBCCDAA" would be encoded as "4A3B2C1D2A".
//
// Implement run-length encoding and decoding.
// You can assume the string to be encoded have no digits and consists solely of alphabetic characters. You can assume the string to be decoded is valid.
//
// String decoding and encoding
// O(N) Time complexity
// O(1) Space complexity
// N is the length of the string
import isNumber from 'is-number';
/**
* Returns the encoding of string
* @param {string} string
* @return {string}
*/
function stringEncoding(string) {
if (string.length === 0) return '';
let currChar = string.charAt(0);
let count = 1;
let encoding = '';
for (let i = 1; i < string.length; i++) {
const char = string.charAt(i);
if (char === currChar) count++;
else {
encoding += count + currChar;
// reset
count = 1;
currChar = char;
}
}
encoding += count + currChar;
return encoding;
}
/**
* Returns the decoding of string
* @param {string} string
* @return {string}
*/
function stringDecoding(string) {
if (string.length === 0) return '';
let currCount = 0;
let i = 0;
let decoding = '';
while (i < string.length) {
const char = string.charAt(i);
if (isNumber(char)) {
const num = Number(char);
currCount = currCount * 10 + num;
} else {
decoding = addCountAmount(decoding, char, currCount);
currCount = 0;
}
i++;
}
return decoding;
}
/**
* Returns the X count of chars to end of string
*/
function addCountAmount(string, char, count) {
for (let i = 1; i <= count; i++) {
string += char;
}
return string;
}
export { stringEncoding, stringDecoding };