Design an algorithm to encode a list of strings to a string. The encoded string is then sent over the network and is decoded back to the original list of strings.

Machine 1 (sender) has the function:

string encode(vector<string> strs) {
// ... your code
return encoded_string;
}

Machine 2 (receiver) has the function:

vector<string> decode(string s) {
//... your code
return strs;
}

So Machine 1 does:

string encoded_string = encode(strs);

and Machine 2 does:

vector<string> strs2 = decode(encoded_string);

strs2 in Machine 2 should be the same as strs in Machine 1.

Implement the encode and decode methods.

Note:

  • The string may contain any possible characters out of 256 valid ascii characters. Your algorithm should be generalized enough to work on any possible characters.
  • Do not use class member/global/static variables to store states. Your encode and decode algorithms should be stateless.
  • Do not rely on any library method such as eval or serialize methods. You should implement your own encode/decode algorithm.

思路:每个字符串之前添加它的长度和一个%字符。

 class Codec {
public: // Encodes a list of strings to a single string.
string encode(vector<string>& strs) {
string res;
for (int i = ; i < strs.size(); i++)
res += std::to_string(strs[i].size()) + "%" + strs[i];
return res;
} // Decodes a single string to a list of strings.
vector<string> decode(string s) {
vector<string> res;
int curInd = ;
int mark = s.find("%");
while (mark != std::string::npos) {
int len = std::stoi(s.substr(curInd, mark - curInd));
if (len) res.push_back(s.substr(mark + , len));
//in case it is an empty string
else res.push_back("");
curInd = mark + len + ;
mark = s.find("%", curInd);
}
return res;
}
}; // Your Codec object will be instantiated and called as such:
// Codec codec;
// codec.decode(codec.encode(strs));

最新文章

  1. C#读取Excel,或者多个excel表,返回dataset
  2. Silverlight:针式打印机文字模糊的改善办法
  3. jQuery.validator 验证规则详解
  4. 关于__IPHONE_OS_VERSION_MAX_ALLOWED和__IPHONE_OS_VERSION_MIN_ALLOWED的用法
  5. Mschat控件示例升级错误处理方法
  6. spring事务的传播性的理解
  7. 201521123082 《Java程序设计》第14周学习总结
  8. NewLife.Net——开始网络编程
  9. 迭代(遍历)时候不可以使用集合的remove和add方法,但可使用Java迭代器的remove和add方法
  10. create-react-app项目添加less配置
  11. 洛谷P3193 [HNOI2008]GT考试(dp 矩阵乘法)
  12. webpack 使用
  13. appium --log-timestamp &gt; appium.log
  14. TP框架做网页静态化
  15. jenkins不能取到svn最新版本问题的解决
  16. stl源码剖析 详细学习笔记 配接器
  17. mybatis中获取参数
  18. Java 第二次实验20145104 张家明
  19. selenium+python自动化93-Chrome报错:Python is likely shutting down
  20. 轻量级ORM框架Dapper应用三:使用Dapper实现In操作

热门文章

  1. linux bash学习(一)
  2. composer应用
  3. Substrings Sort string 基本操作
  4. centos关闭ipv6
  5. Quartus ModelSim联合仿真中的RAM初始化
  6. swift方法 的写法,ui上拖拽的控件到controller里面的方法
  7. python面向对象之继承与派生
  8. [Leetcode Week5]Word Ladder
  9. Shell中的while循环【转】
  10. 设计模式之笔记--简单工厂模式(Simple Factory)