File tree Expand file tree Collapse file tree 1 file changed +58
-0
lines changed
encode-and-decode-strings Expand file tree Collapse file tree 1 file changed +58
-0
lines changed Original file line number Diff line number Diff line change
1
+ /* *
2
+ * Let's say sum of lengths of given strings N, and the length of the longest string M
3
+ *
4
+ * Encode
5
+ * - Time complexity: O(N)
6
+ * - Space complexity: O(1)
7
+ *
8
+ * Decode
9
+ * - Time complexity: O(N)
10
+ * - Space complexity: O(M)
11
+ */
12
+
13
+ class Codec {
14
+ public:
15
+
16
+ // Encodes a list of strings to a single string.
17
+ string encode (vector<string>& strs) {
18
+ string res = " " ;
19
+ for (auto str : strs) {
20
+ res += to_string (str.size ());
21
+ res.push_back (' .' );
22
+ res += str;
23
+ }
24
+ return res;
25
+ }
26
+
27
+ // Decodes a single string to a list of strings.
28
+ vector<string> decode (string s) {
29
+ vector<string> res;
30
+ int str_size = 0 ;
31
+ string tmp = " " ;
32
+
33
+ auto it = s.begin ();
34
+ while (it != s.end ()) {
35
+ do {
36
+ str_size = str_size * 10 + (*it - ' 0' );
37
+ it++;
38
+ } while (*it != ' .' );
39
+
40
+ it++;
41
+
42
+ for (int i = 0 ; i < str_size; i++) {
43
+ tmp.push_back (*it);
44
+ it++;
45
+ }
46
+
47
+ res.push_back (tmp);
48
+ str_size = 0 ;
49
+ tmp = " " ;
50
+ }
51
+
52
+ return res;
53
+ }
54
+ };
55
+
56
+ // Your Codec object will be instantiated and called as such:
57
+ // Codec codec;
58
+ // codec.decode(codec.encode(strs));
You can’t perform that action at this time.
0 commit comments