Ai
1 Star 2 Fork 5

LilithSangreal/LeetCode-Solutions

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
encode-and-decode-strings.cpp 1.06 KB
一键复制 编辑 原始数据 按行查看 历史
kamyu 提交于 2015-08-30 15:14 +08:00 . Create encode-and-decode-strings.cpp
// Time: O(n)
// Space: O(1)
class Codec {
public:
// Encodes a list of strings to a single string.
string encode(vector<string>& strs) {
string s;
for (size_t i = 0; i < strs.size(); ++i) {
size_t len = strs[i].length();
string tmp;
for (size_t i = 0, mask = 0xff; i < sizeof(size_t); ++i, mask <<= 8) {
tmp.push_back(len & mask);
}
reverse(tmp.begin(), tmp.end());
s.append(tmp);
s.append(strs[i]);
}
return s;
}
// Decodes a single string to a list of strings.
vector<string> decode(string s) {
vector<string> strs;
size_t pos = 0;
while (pos + sizeof(size_t) <= s.length()) {
size_t len = 0;
for (size_t i = 0; i < sizeof(size_t); ++i) {
len <<= 8;
len += static_cast<unsigned char>(s[pos++]);
}
strs.push_back(s.substr(pos, len));
pos += len;
}
return strs;
}
};
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/LilithSangreal/LeetCode-Solutions.git
git@gitee.com:LilithSangreal/LeetCode-Solutions.git
LilithSangreal
LeetCode-Solutions
LeetCode-Solutions
master

搜索帮助