-
Notifications
You must be signed in to change notification settings - Fork 22
/
271.encode-and-decode-strings.cpp
65 lines (56 loc) · 1.36 KB
/
271.encode-and-decode-strings.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
64
65
class Codec {
public:
// Encodes a list of strings to a single string.
string encode(vector<string>& strs) {
string res;
for (auto i = 0; i < strs.size(); ++i)
{
for(auto j = 0; j < strs[i].size(); ++j)
{
if (strs[i][j] == '|')
{
res += "||";
}
else
{
res += strs[i][j];
}
}
res += "|+";
}
return res;
}
// Decodes a single string to a list of strings.
vector<string> decode(string s) {
vector<string> res;
string word = "";
for (auto i = 0; i < s.size(); ++i)
{
if (s[i] == '|')
{
if (s[i + 1] == '+')
{
res.push_back(word);
word = "";
}
else
{
word += s[i + 1];
}
i++;
}
else
{
word += s[i];
}
}
if (word.size() > 0)
{
res.push_back(word);
}
return res;
}
};
// Your Codec object will be instantiated and called as such:
// Codec codec;
// codec.decode(codec.encode(strs));