encode-and-decode-string 1.0.0
Encode and Decode String
Loading...
Searching...
No Matches
main.cpp
Go to the documentation of this file.
1#include <bits/stdc++.h>
2
3using namespace std;
4
6{
7public:
8 /*
9 * @param strs: a list of strings
10 * @return: encodes a list of strings to a single string.
11 */
12 string encode(vector<string> &strs)
13 {
14 string encoded("");
15 for (const string& el: strs)
16 encoded += el + ":;";
17 return encoded;
18 }
19
20 /*
21 * @param str: A string
22 * @return: decodes a single string to a list of strings
23 */
24 vector<string> decode(string &str)
25 {
26 if (str.empty())
27 return {};
28 list<string> decoded_list;
29 int start_index = 0;
30 for (int i = 0; i < (int)str.length(); ++i)
31 {
32 if (str[i] == ';' && i >= 1 && str[i - 1] == ':')
33 {
34 decoded_list.push_back(str.substr(start_index, ((i - 1) - start_index)));
35 start_index = i + 1;
36 }
37 }
38 if (decoded_list.empty())
39 return {str};
40 return vector<string>(decoded_list.begin(), decoded_list.end());
41 }
42};
43
44int main()
45{
46 vector<string> input = {"leet", "code", "love", "you"};
47 cout << "input: " << '\n';
48 for (string& s: input)
49 cout << s << " ";
50 cout << '\n';
51
52 string encoded = Solution().encode(input);
53 cout << "encoded: " << encoded << '\n';
54
55 vector<string> output = Solution().decode(encoded);
56 cout << "output: " << '\n';
57 for (string& s: output)
58 cout << s << " ";
59 cout << '\n';
60
61 return 0;
62}
string encode(vector< string > &strs)
Definition main.cpp:12
vector< string > decode(string &str)
Definition main.cpp:24
int main()
Definition main.cpp:44