Skip to content
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 43 additions & 0 deletions encode-and-decode-strings/PDKhan.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
class Solution {
public:
/*
* @param strs: a list of strings
* @return: encodes a list of strings to a single string.
*/
string encode(vector<string> &strs) {
// write your code here
string code;

for(const string& s : strs){
code += to_string(s.size()) + ":" + s;
}

return code;
}

/*
* @param str: A string
* @return: decodes a single string to a list of strings
*/
vector<string> decode(string &str) {
// write your code here
vector<string> result;
int i;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

int i = 0;


while(i < str.size()){
int j = i;

while(str[j] != ':')
j++;

int len = stoi(str.substr(i, j - i);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

int len = stoi(str.substr(i, j - i));

string word = str.substr(j + 1, len);

result.push_back(word);

i = j + 1 + len;
}

return result;
}
};