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