-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path271 EncodeandDecodeStrings.cpp
63 lines (48 loc) · 1.28 KB
/
271 EncodeandDecodeStrings.cpp
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
class Solution {
public:
string encode(vector<string>& strs) {
int len = 0;
for(const string& str : strs)
len += numDigits(str.length()) + 1 + str.length();
string s(len, ';');
int index = 0;
for(const string& str : strs) {
len = str.length();
do {
s[index++] = '0' + len % 10;
len /= 10;
} while(len);
++index;
for(const char& c : str)
s[index++] = c;
}
return s;
}
vector<string> decode(string s) {
vector<string> strs;
int len = s.length(), numChars = 0, tens = 1;
for(int i = 0; i < len; ++i) {
if(s[i] == ';') {
strs.push_back(string(numChars, ' '));
for(int j = 0; j < numChars; ++j)
strs.back()[j] = s[++i];
numChars = 0;
tens = 1;
}
else {
numChars += tens * (s[i] - '0');
tens *= 10;
}
}
return strs;
}
private:
int numDigits(int n) {
int digits = 0;
do {
++digits;
n /= 10;
} while(n);
return digits;
}
};