您的位置:首页 > 其它

LeetCode 271. Encode and Decode Strings

2016-05-24 12:41 141 查看
This is to encode the string not to COMPRESS the string.

This is one possible answer.

#include <string>
#include <vector>
#include <iostream>
using namespace std;

string encode(vector<string>& strs) {
string res = "";
for(int i = 0; i < strs.size(); ++i) {
res += to_string(strs[i].size()) + "#" + strs[i];
}
return res;
}

vector<string> decode(string s) {
vector<string> res;
int i = 0, j = 0;
while(i < s.size()) {
if(s[i] != '#') {i++; continue;}
else {
int len = stoi(s.substr(j, i - j));
res.push_back(s.substr(i + 1, len));
i = i + 1 + len;
j = i;
}
}
//while(s.size() > 0) {
//  int pos = s.find_first_of('#');   // if not know this function, better to use two pointers.
//  int len = stoi(s.substr(0, pos));
//  res.push_back(s.substr(pos + 1, len));
//  s = s.substr(pos + len + 1);
//}
return res;
}

int main(void) {
vector<string> words{"tammy", "is", "a", "good", "girl"};
string s = encode(words);
cout << endl;
vector<string> res = decode(s);
for(int i = 0; i < res.size(); ++i) cout << res[i] << endl;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: