File tree Expand file tree Collapse file tree 1 file changed +43
-0
lines changed
encode-and-decode-strings Expand file tree Collapse file tree 1 file changed +43
-0
lines changed Original file line number Diff line number Diff line change 1+ class Solution {
2+ public:
3+ /*
4+ * @param strs: a list of strings
5+ * @return: encodes a list of strings to a single string.
6+ */
7+ string encode (vector<string> &strs) {
8+ // write your code here
9+ string code;
10+
11+ for (const string& s : strs){
12+ code += to_string (s.size ()) + " :" + s;
13+ }
14+
15+ return code;
16+ }
17+
18+ /*
19+ * @param str: A string
20+ * @return: decodes a single string to a list of strings
21+ */
22+ vector<string> decode (string &str) {
23+ // write your code here
24+ vector<string> result;
25+ int i;
26+
27+ while (i < str.size ()){
28+ int j = i;
29+
30+ while (str[j] != ' :' )
31+ j++;
32+
33+ int len = stoi (str.substr (i, j - i);
34+ string word = str.substr (j + 1 , len);
35+
36+ result.push_back (word);
37+
38+ i = j + 1 + len;
39+ }
40+
41+ return result;
42+ }
43+ };
You can’t perform that action at this time.
0 commit comments