设计一种算法,将字符串列表编码为字符串。 编码后的字符串然后通过网络发送并解码回原始字符串列表。
- 时间复杂度O(n),空间复杂度O(1)
- Runtime: 96 ms, faster than 71.78%
- Memory Usage: 44.5 MB, less than 71.78%
/**
* Encodes a list of strings to a single string.
*
* @param {string[]} strs
* @return {string}
*/
var encode = function(strs) {
return strs.reduce((res, cur) => {
return res+= (cur.length + '|' + cur);
}, '')
};
/**
* Decodes a single string to a list of strings.
*
* @param {string} s
* @return {string[]}
*/
var decode = function(s) {
const res = [];
while (s) {
const index = s.indexOf('|');
const len = parseInt(s.substr(0, index));
res.push(s.substring(index + 1, index + len + 1))
s = s.substr(index + len + 1);
}
return res;
};
/**
* Your functions will be called as such:
* decode(encode(strs));
*/
网友评论