题目描述
将字符串列表编码为单个字符串。
将单个字符串解码为字符串列表。
不允许您使用任何序列化方法(例如 eval)来解决问题。
样例
5#helloWorld
[hello,World]
算法1
neetcode$
C++ 代码
class Codec {
public:
// Encodes a list of strings to a single string.
string encode(vector<string>& strs) {
string res = "";
for(auto c: strs){
//eg: 5#hello
res += to_string(c.size()) + "#" + c;//用非英文字符分割
}
return res;
}
// Decodes a single string to a list of strings.
vector<string> decode(string s) {
vector<string> res;
int i = 0;
auto length = 0;
while(i < s.size()){
int j = i;
while(isdigit(s[j])){
j++;
}
//s.substr(i, j - i),从s中提取一个子串,i是起点,j - i是子串长度
//stoi():将字符串转化为整数
length = stoi(s.substr(i, j - i));
//提取长度为length的子串并转化为整数
string str = s.substr(j + 1, length);
res.push_back(str);
i = j + 1 + length;//更新i
}
return res;
}
};