Skip to content

Commit 124da3b

Browse files
committed
Endcode and Decode Strings solution
1 parent 62af3c6 commit 124da3b

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed

encode-and-decode-strings/PDKhan.cpp

+43
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
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+
};

0 commit comments

Comments
 (0)